<template>
  <el-scrollbar height="calc(100vh - 100px)">
  <div class="outer">
    <div class="box">
      <!-- 优化后的卡片布局 -->
      <el-card class="report-header-card">
        <div class="report-header-content">
          <!-- 任务基本信息 -->
          <div class="task-info-section">
            <div class="task-title-area">
              <div class="task-title-container">
                <el-button
                  class="task-name-button"
                  type="text"
                  @click="editTaskName"
                  @click.stop
                >
                  {{ taskName }}
                  <el-icon class="edit-icon"><Edit /></el-icon>
                </el-button>
                <el-tag
                  v-if="taskType=== '已完成'"
                  class="task-status-tag success"
                  effect="light">
                  {{taskType}}
                </el-tag>
                <el-tag
                  v-if="taskType=== '运行中'"
                  class="task-status-tag running"
                  effect="light">
                  {{taskType}}
                </el-tag>
                <el-tag
                  v-if="taskType=== '运行失败'"
                  class="task-status-tag error"
                  effect="light">
                  {{taskType}}
                </el-tag>
              </div>
            </div>
              <div class="task-description">
                  <div class="desc-text">结果分析：{{ desc }}</div>
              </div>
              <el-input
                v-if="inputDlg && editingField === 'taskName'"
                v-model="taskName"
                @blur="cancelEditing"
                ref="input"
                size="small"
                class="task-name-input"
                @click.stop
              />
          </div>
          <!-- 性能指标卡片 -->
          <div class="metrics-section">
            <div class="metric-card">
              <div class="metric-icon">
                <icon
                  icon="grommet-icons:performance"
                  font-size="28">
                </icon>
              </div>
              <div class="metric-content">
                <div class="metric-title">性能指标</div>
                <div class="metric-values">
                  <div class="metric-item">
                    <span class="metric-label">平均TPS：</span>
                    <span class="metric-value">{{ (reportData.avgTps || 0).toFixed(2) }}</span>
                  </div>
                  <div class="metric-item">
                    <span class="metric-label">平均响应时间：</span>
                    <span class="metric-value">{{formatResponseTime(reportData.avgResponseTime)}}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="metric-card">
              <div class="metric-icon">
                <icon
                  icon="grommet-icons:cpu"
                  font-size="28">
                </icon>
              </div>
              <div class="metric-content">
                <div class="metric-title">系统资源</div>
                <div class="metric-values">
                  <div class="metric-item">
                    <span class="metric-label">执行结束后CPU：</span>
                    <span class="metric-value">{{getCurrentCpuUsage()}}%</span>
                  </div>
                  <div class="metric-item">
                    <span class="metric-label">执行结束后内存：</span>
                    <span class="metric-value">{{getCurrentMemoryUsage()}}%</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="metric-card">
              <div class="metric-icon">
                <icon
                  icon="el:user"
                  font-size="28">
                </icon>
              </div>
              <div class="metric-content">
                <div class="metric-title">创建信息</div>
                <div class="metric-values">
                  <div class="metric-item">
                    <span class="metric-label">创建人：</span>
                    <span class="metric-value">{{reportData.executor || '未知'}}</span>
                  </div>
                  <div class="metric-item">
                    <span class="metric-label">创建时间：</span>
                    <span class="metric-value">{{formatTime(reportData.create_time)}}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="metric-card">
              <div class="metric-icon">
                <icon
                  icon="el:time"
                  font-size="28">
                </icon>
              </div>
              <div class="metric-content">
                <div class="metric-title">运行信息</div>
                <div class="metric-values">
                  <div class="metric-item">
                    <span class="metric-label">运行时长：</span>
                    <span class="metric-value">{{formatDuration(reportData.duration)}}</span>
                  </div>
                  <div class="metric-item">
                    <span class="metric-label">错误率：</span>
                    <span class="metric-value">{{reportData.errorRate || 0}}%</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- Tab导航和操作按钮 -->
      <div class="tab-navigation-container">
        <el-menu
          :default-active="activeIndex"
          mode="horizontal"
          @select="handleSelect"
          class="report-tabs"
        >
          <el-menu-item index="1">指标详情</el-menu-item>
          <el-menu-item index="2">GUI</el-menu-item>
          <el-menu-item index="3">压力机监控</el-menu-item>
          <el-menu-item index="4">被测服务监控</el-menu-item>
          <el-menu-item index="5">日志</el-menu-item>
        </el-menu>

        <!-- 操作按钮组 -->
        <div class="action-buttons">
          <el-button type="info" @click="back" class="action-btn">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <el-button type="primary" @click="saveReport" class="action-btn">
            <el-icon><Check /></el-icon>
            保存
          </el-button>

          <!-- 导出下拉菜单 -->
          <el-dropdown trigger="click" @command="handleExportCommand" class="action-dropdown">
            <el-button type="primary" :disabled="!reportData.id" class="action-btn">
              导出<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="excel">
                  <el-icon><Document /></el-icon>导出Excel报告
                </el-dropdown-item>
                <el-dropdown-item command="html">
                  <el-icon><Monitor /></el-icon>生成HTML报告
                </el-dropdown-item>
                <el-dropdown-item command="pdf">
                  <el-icon><DocumentCopy /></el-icon>导出PDF报告
                </el-dropdown-item>
                <el-dropdown-item command="raw">
                  <el-icon><Files /></el-icon>导出原始数据
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 通知按钮 -->
          <el-button @click="showNotificationDialog" type="success" class="action-btn">
            <el-icon><Bell /></el-icon>
            通知
          </el-button>

          <!-- 更多操作 -->
          <el-dropdown trigger="click" @command="handleMoreCommand" class="action-dropdown">
            <el-button type="info" class="action-btn">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="baseline">
                  <el-icon><TrendCharts /></el-icon>创建基准线
                </el-dropdown-item>
                <el-dropdown-item command="compare">
                  <el-icon><DataAnalysis /></el-icon>与基准线对比
                </el-dropdown-item>
                <el-dropdown-item command="analyze">
                  <el-icon><PieChart /></el-icon>性能分析
                </el-dropdown-item>
                <el-dropdown-item command="config">
                  <el-icon><Setting /></el-icon>查看压测配置
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <div v-if="activeIndex === '1'" class="munu">
        <div style="display: flex; align-items: center; justify-content: space-between;">
          <div class="title-info">
              <el-divider direction="vertical" class="divider" />
              压测信息
          </div>
          <div style="display: flex; align-items: center;">
              <el-button v-if="taskType === '运行中'" class="runStop" type="warning" @click="stopPerformanceTest">
                  <el-icon><SwitchButton /></el-icon>
                  <span style="margin-left: 5px">暂停运行</span>
              </el-button>
              <el-button v-else class="runStop" type="success" @click="rerunTest">
                  <el-icon><SwitchButton /></el-icon>
                  <span style="margin-left: 5px">重新运行</span>
              </el-button>
          </div>
        </div>
        <div class="spacing">
          <span>任务类型：{{getTaskTypeText(reportData.taskType || reportData.task?.taskType)}}</span>
          <span>压测模式：{{getRunPatternText(reportData.taskType)}}</span>
          <span>控制模式：{{getDistributedModeText(reportData.task?.distributed_mode)}}</span>
          <span>并发用户数：{{getCurrentUserCount()}}</span>
          <span>总请求数：{{reportData.totalRequests || 0}}</span>
          <span>成功请求数：{{reportData.successRequests || 0}}</span>
        </div>
        <el-button
          style="margin-right: 25px;position: relative;margin-top: 10px"
          :type="isFilterMode ? 'warning' : 'success'"
          @click="toggleFilterMode">
          <el-icon><View /></el-icon>
          <span style="margin-left: 5px">{{ isFilterMode ? '显示全部' : '仅查看' }}</span>
        </el-button>
        <div class="table-desc" >
          <span>Max(ms)：最大响应时间</span>
          <span>Min(ms)：最小响应时间</span>
          <span>Avg(ms)：平均响应时间</span>
          <span>90%ile(ms)：90%响应时间线</span>
          <span>99%ile(ms)：99%响应时间线</span>
          <span>平均RPS：平均每秒请求数</span>
          <span>平均TPS：平均每秒处理事务数</span>
        </div>
        <div style="margin-bottom: 30px">
          <el-table
            ref="table"
            :data="filteredMetrics"
            style="width: 100%"
            border
            empty-text="暂无性能指标数据，请等待测试执行或测试完成后查看"
            @selection-change="handleSelectionChange"
            :row-key="row => row.method + '_' + row.name"
            :reserve-selection="true"
            @row-click="handleRowClick">
            <el-table-column
              type="selection"
              width="55"
              :selectable="row => row.method !== 'ALL'"
            ></el-table-column>
            <el-table-column prop="name" label="接口名称" align="center" min-width="300" >
              <template #default="scope">
                <el-tooltip :content="scope.row.name" placement="top">
                  <span class="interface-name">{{ scope.row.name }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="totalRequests" label="总请求数" width="120" align="center"></el-table-column>
            <el-table-column prop="successRequests" label="请求成功数" align="center" width="110"></el-table-column>
            <el-table-column prop="failedRequests" label="请求失败数" align="center" width="110"></el-table-column>
            <el-table-column prop="currentUsers" label="并发用户数" align="center" width="110">
              <template #default="scope">
                {{ getUserCountForRow(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column prop="maxResponseTime" label="Max(ms)" align="center" width="100"></el-table-column>
            <el-table-column prop="minResponseTime" label="Min(ms)" align="center" width="100"></el-table-column>
            <el-table-column prop="avgResponseTime" label="Avg(ms)" align="center" width="100"></el-table-column>
            <el-table-column prop="p50ResponseTime" label="50%ile(ms)" align="center" width="110"></el-table-column>
            <el-table-column prop="p90ResponseTime" label="90%ile(ms)" align="center" width="110"></el-table-column>
            <el-table-column prop="p95ResponseTime" label="95%ile(ms)" align="center" width="110"></el-table-column>
            <el-table-column prop="p99ResponseTime" label="99%ile(ms)" align="center" width="110"></el-table-column>
            <el-table-column prop="avgRps" label="平均RPS" align="center" width="100"></el-table-column>
            <el-table-column prop="avgTpsAvg" label="平均TPS" align="center" width="100"></el-table-column>
            <el-table-column prop="errorRate" label="错误率%" align="center" width="110">
              <template #default="scope">
                <el-tag class="task-status-tag danger" v-if="scope.row.errorRate > 5" type="danger">{{scope.row.errorRate}}%</el-tag>
                <el-tag class="task-status-tag warning" v-else-if="scope.row.errorRate > 1" type="warning">{{scope.row.errorRate}}%</el-tag>
                <el-tag class="task-status-tag success" v-else type="success">{{scope.row.errorRate}}%</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="charts-container">
          <div class="chart-wrapper">
            <ResponseTimeChart
              chartTitle="平均响应时间"
              chartWidth="100%"
              chartHeight="350px"
              chartUnit="单位(毫秒)"
              :xData="xData"
              :seriesData="responseTimeSeriesData"
              :key="'response-time-' + chartUpdateKey"
              chartType="responseTime"
            />
          </div>
          <div class="chart-wrapper">
            <ResponseTimeChart
              chartTitle="每秒请求数(RPS)"
              chartWidth="100%"
              chartHeight="350px"
              chartUnit="单位(个)"
              :xData="xData"
              :seriesData="rpsSeriesData"
              :key="'rps-' + chartUpdateKey"
              chartType="rps"
            />
          </div>
          <div class="chart-wrapper">
            <ResponseTimeChart
              chartTitle="每秒处理事务数(TPS)"
              chartWidth="100%"
              chartHeight="350px"
              chartUnit="单位(个)"
              :xData="xData"
              :seriesData="tpsSeriesData"
              :key="'tps-' + chartUpdateKey"
              chartType="tps"
            />
          </div>
          <div class="chart-wrapper">
            <ResponseTimeChart
              chartTitle="并发用户数"
              chartWidth="100%"
              chartHeight="350px"
              chartUnit="单位(个)"
              :xData="xData"
              :seriesData="usersSeriesData"
              :key="'users-' + chartUpdateKey"
              chartType="users"
            />
          </div>
          <div class="chart-wrapper">
            <ResponseTimeChart
              chartTitle="90%响应时间线"
              chartWidth="100%"
              chartHeight="350px"
              chartUnit="单位(毫秒)"
              :xData="xData"
              :seriesData="p90SeriesData"
              :key="'p90-' + chartUpdateKey"
              chartType="p90"
            />
          </div>
          <div class="chart-wrapper">
            <ResponseTimeChart
              chartTitle="99%响应时间线"
              chartWidth="100%"
              chartHeight="350px"
              chartUnit="单位(毫秒)"
              :xData="xData"
              :seriesData="p99SeriesData"
              :key="'p99-' + chartUpdateKey"
              chartType="p99"
            />
          </div>
        </div>
        <div class="title-info" style="margin-top: 30px;"><el-divider direction="vertical" class="divider"/>结果分析
          <el-button :disabled="!isEdit" @click="startEditing" type="primary" size="small" style="margin-left: 10px;">编辑</el-button>
        </div>
        <el-input
            style="font-size: 14px; margin-top: 15px;"
            :rows="8"
            type="textarea"
            v-if="inputDlg && editingField === 'desc'"
            v-model="desc"
            @blur="saveAnalysis"
            ref="input"
            @click.stop
            placeholder="请输入测试结果分析..."
        />
        <p class="p_text" v-else-if="!inputDlg || editingField !== 'desc'" style="margin-top: 15px; line-height: 1.8;">{{desc}}</p>
      </div>
      <div v-show="activeIndex === '2'" class="munu">
        <div class="gui-controls">
          <div class="title-info">
            <el-divider direction="vertical" class="divider" />
            GUI监控
            <el-button
              :type="getTestStatusType()"
              size="small"
              effect="light">
              {{ getTestStatusText() }}
            </el-button>

          </div>
          <div class="gui-server-selection" v-if="getTestStatusText() ==='运行中'">
            <el-button
              type="success"
              @click="refreshGUI"
              size="small">
              刷新GUI
            </el-button>
          </div>
        </div>

        <!-- 测试未运行时的提示 -->
        <div v-if="!isTestRunning" class="test-not-running">
          <el-alert
            title="测试未运行"
            :description="getTestNotRunningMessage()"
            type="info"
            show-icon
            :closable="false">
          </el-alert>
        </div>

        <!-- GUI界面区域 -->
        <div v-else-if="guiUrl" class="iframe-container">
          <iframe
            :src="guiUrl"
            @load="handleIframeLoad"
            @error="handleIframeError"
            >
          </iframe>
          <div v-if="iframeError" class="iframe-error">
            <el-alert
              title="GUI加载失败"
              :description="iframeErrorMessage"
              type="error"
              show-icon>
              <template #default>
                <div style="margin-top: 10px;">
                  <p>可能的原因：</p>
                  <ul style="margin: 5px 0; padding-left: 20px;">
                    <li>测试服务未正确启动</li>
                    <li>服务器不可访问</li>
                    <li>测试已结束，GUI界面已关闭</li>
                  </ul>
                </div>
              </template>
            </el-alert>
            <div style="margin-top: 10px; text-align: center;">
              <el-button type="primary" @click="retryLoadGUI">
                重试加载
              </el-button>
            </div>
          </div>
        </div>

        <!-- 无GUI配置时的提示 -->
        <div v-else class="no-gui-message">
          <el-empty description="无可用的GUI界面">
            <p>后端未提供GUI URL，可能该测试没有可视化界面</p>
          </el-empty>
        </div>
      </div>
      <div v-if="activeIndex === '3'" class="munu">
        <div class="title-info">
          <el-divider direction="vertical" class="divider" />
          压力机监控
          <el-button type="primary" size="small" @click="refreshMonitoringData">刷新数据</el-button>
          <!-- WebSocket连接状态指示器 -->
          <div class="ws-status-indicator">
            <el-tooltip :content="getWebSocketStatusText()" placement="top">
              <el-tag
                :type="getWebSocketStatusType()"
                class="task-status-tag info"
                size="small"
                effect="light"
                @click="handleWebSocketStatusClick"
                style="cursor: pointer;">
                <el-icon><View /></el-icon>
                {{ getWebSocketStatusText() }}
              </el-tag>
            </el-tooltip>
          </div>
        </div>
        <div class="monitor-grid">
          <div class="monitor-card">
            <h4>系统资源</h4>
            <div class="metric-item">
              <span>CPU使用率:</span>
              <span :class="getCpuLevelClass(monitoringData.cpu_percent)">{{monitoringData.cpu_percent || 0}}%</span>
            </div>
            <div class="metric-item">
              <span>内存使用率:</span>
              <span :class="getMemoryLevelClass(monitoringData.memory_percent)">{{monitoringData.memory_percent || 0}}%</span>
            </div>
            <div class="metric-item">
              <span>磁盘使用率:</span>
              <span>{{monitoringData.disk_percent || 0}}%</span>
            </div>
            <div class="metric-item">
              <span>网络IO:</span>
              <span>↑{{formatBytes(monitoringData.network_sent)}} ↓{{formatBytes(monitoringData.network_recv)}}</span>
            </div>
          </div>
          <div class="monitor-card">
            <h4>压力机状态</h4>
            <div class="metric-item">
              <span>活跃连接数:</span>
              <span>{{monitoringData.active_connections || 0}}</span>
            </div>
            <div class="metric-item">
              <span>当前RPS:</span>
              <span>{{monitoringData.current_rps || 0}}</span>
            </div>
            <div class="metric-item">
              <span>当前用户数:</span>
              <span>{{monitoringData.current_users || 0}}</span>
            </div>
            <div class="metric-item">
              <span>错误率:</span>
              <span :class="getErrorRateClass(monitoringData.error_rate)">{{monitoringData.error_rate || 0}}%</span>
            </div>
          </div>
          <div class="monitor-card">
            <h4>服务器信息</h4>
            <div class="metric-item">
              <span>服务器类型:</span>
              <span>{{monitoringData.server_type || 'single'}}</span>
            </div>
            <div class="metric-item">
              <span>CPU核心数:</span>
              <span>{{monitoringData.cpu_cores || 'N/A'}}</span>
            </div>
            <div class="metric-item">
              <span>总内存:</span>
              <span>{{formatBytes(monitoringData.total_memory)}}</span>
            </div>
            <div class="metric-item">
              <span>运行时长:</span>
              <span>{{formatDuration(monitoringData.uptime)}}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="activeIndex === '4'" class="munu">
        <div >
          <!-- 新增：监控链接输入 -->
          <el-input
            v-model="monitorUrl"
            placeholder="输入被测服务监控页面URL"
            size="small"
            style="width: 320px; margin-left: 20px;"
            @keyup.enter="setMonitorIframeUrl"
            clearable
          />
          <el-button type="success" size="small" @click="setMonitorIframeUrl" style="margin-left: 8px;">确定</el-button>
          <el-button type="info" size="small" @click="resetMonitorIframeUrl" style="margin-left: 4px;">重置</el-button>
        </div>
        <!-- 新增：iframe展示区 -->
        <div v-if="monitorIframeUrl" style="margin-top: 18px;">
          <iframe
            :src="monitorIframeUrl"
            style="width: 100%; min-height: 600px; border: 1px solid #eee; border-radius: 8px;"
            frameborder="0"
          ></iframe>
        </div>
      </div>
      <div v-if="activeIndex === '5'" class="munu">
        <div class="title-info">
          <el-divider direction="vertical" class="divider" />
          实时日志
          <el-button type="primary" size="small" @click="refreshLogData">刷新日志</el-button>
          <el-button type="warning" size="small" @click="clearLogs">清空日志</el-button>
          <el-switch
            v-model="autoRefresh"
            @change="toggleAutoRefresh"
            active-text="自动刷新"
            inactive-text="手动刷新">
          </el-switch>
        </div>
        <div class="log-controls">
          <el-input
            v-model="logFilter"
            placeholder="过滤日志..."
            size="small"
            style="width: 200px; margin-right: 10px;"
            clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="logLevel" placeholder="日志级别" size="small" style="width: 120px; margin-right: 10px;">
            <el-option label="全部" value="all"></el-option>
            <el-option label="debug" value="debug"></el-option>
            <el-option label="info" value="info"></el-option>
            <el-option label="warning" value="warning"></el-option>
            <el-option label="error" value="error"></el-option>
          </el-select>
          <el-select v-model="logCategory" placeholder="日志类型" size="small" style="width: 120px; margin-right: 10px;">
            <el-option 
              v-for="(label, value) in logCategories" 
              :key="value" 
              :label="label" 
              :value="value">
            </el-option>
          </el-select>
          <el-tag class="task-status-tag info" type="info">共 {{filteredLogs.length}} 条日志</el-tag>
        </div>
        <div class="log-container">
          <div v-for="(log, index) in filteredLogs" :key="index" :class="getLogClass(log.level)" class="log-item">
            <span class="log-time">[{{formatTime(log.timestamp)}}]</span>
            <span class="log-level">[{{log.level.toUpperCase()}}]</span>
            <span class="log-category" v-if="log.category">
              <el-icon :size="14"><component :is="getLogCategoryIcon(log.category)" /></el-icon>
            </span>
            <!-- 格式化的请求日志 -->
            <template v-if="log.formatted && log.formatted.isFormatted">
              <span :class="getMethodClass(log.formatted.method)" class="log-method">{{log.formatted.method}}</span>
              <span class="log-url">{{log.formatted.url}}</span>
              <span v-if="log.formatted.status" :class="getStatusClass(log.formatted.status)" class="log-status">{{log.formatted.status}}</span>
            </template>
            <!-- 普通日志消息 -->
            <span v-else class="log-message">{{log.message}}</span>
            <!-- 详细信息展开按钮 -->
            <el-button 
              v-if="log.details" 
              type="text" 
              size="small" 
              @click="log.showDetails = !log.showDetails" 
              class="details-toggle">
              {{ log.showDetails ? '收起' : '详情' }}
            </el-button>
            <!-- 详细信息展示区 -->
            <div v-if="log.details && log.showDetails" class="log-details">
              <pre>{{log.details}}</pre>
            </div>
          </div>
          <div v-if="filteredLogs.length === 0" class="no-logs">
            <div class="empty-log-content">
              <el-icon class="empty-log-icon"><Document /></el-icon>
              <p class="empty-log-text">暂无日志数据</p>
              <p class="empty-log-hint">日志将在测试运行时实时显示</p>
            </div>
          </div>
        </div>
      </div>
  </div>
  </div>
  </el-scrollbar>

  <!-- 性能分析结果对话框 -->
  <el-dialog
    v-model="analysisDialogData.visible"
    title="性能分析报告"
    width="60%"
    :destroy-on-close="true"
  >
    <div class="analysis-dialog-content">
      <div class="analysis-section">
        <h4>性能得分</h4>
        <div class="score-display">
          <el-progress
            type="circle"
            :percentage="analysisDialogData.performance_score"
            :color="getScoreColor(analysisDialogData.performance_score)"
            :width="120"
          >
            <template #default="{ percentage }">
              <span class="score-text">{{ percentage }}/100</span>
            </template>
          </el-progress>
        </div>
      </div>

      <div class="analysis-section">
        <h4>发现的瓶颈</h4>
        <div v-if="analysisDialogData.bottlenecks.length > 0">
          <el-alert
            v-for="(bottleneck, index) in analysisDialogData.bottlenecks"
            :key="index"
            :title="bottleneck.type"
            :description="bottleneck.description"
            :type="getSeverityType(bottleneck.severity)"
            show-icon
            style="margin-bottom: 10px;"
          />
        </div>
        <el-empty v-else description="未发现明显性能瓶颈" />
      </div>

      <div class="analysis-section">
        <h4>优化建议</h4>
        <div v-if="analysisDialogData.recommendations.length > 0">
          <ul class="recommendations-list">
            <li
              v-for="(recommendation, index) in analysisDialogData.recommendations"
              :key="index"
              class="recommendation-item"
            >
              <el-icon class="recommendation-icon"><Check /></el-icon>
              {{ recommendation }}
            </li>
          </ul>
        </div>
        <el-empty v-else description="暂无优化建议" />
      </div>
    </div>
  </el-dialog>

  <!-- 测试配置详情对话框 -->
  <el-dialog
    v-model="configDialogData.visible"
    title="压测配置详情"
    width="80%"
    :destroy-on-close="true"
  >
    <div class="config-dialog-content" v-if="configDialogData.taskConfig">
      <!-- 基础配置 -->
      <el-card class="config-section" shadow="never">
        <template #header>
          <div class="config-section-title">
            <el-icon><Setting /></el-icon>
            基础配置
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">任务名称：</span>
              <span class="config-value">{{ configDialogData.taskConfig.taskName || '未设置' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">任务类型：</span>
              <span class="config-value">{{ getTaskTypeText(configDialogData.taskConfig.taskType) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">压测模式：</span>
              <span class="config-value">{{ getRunPatternText(configDialogData.taskConfig.runPattern) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">控制模式：</span>
              <span class="config-value">{{ getDistributedModeText(configDialogData.taskConfig.distributed_mode) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">创建人：</span>
              <span class="config-value">{{ configDialogData.taskConfig.creator || '未知' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">创建时间：</span>
              <span class="config-value">{{ formatTime(configDialogData.taskConfig.create_time) }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 性能参数 -->
      <el-card class="config-section" shadow="never">
        <template #header>
          <div class="config-section-title">
            <el-icon><DataAnalysis /></el-icon>
            性能参数
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">并发用户数：</span>
              <span class="config-value">{{ configDialogData.taskConfig.concurrent_users || configDialogData.taskConfig.users || '未设置' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">持续时间：</span>
              <span class="config-value">{{ configDialogData.taskConfig.duration || '未设置' }}秒</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">爬坡时间：</span>
              <span class="config-value">{{ configDialogData.taskConfig.spawn_rate || configDialogData.taskConfig.ramp_up || '未设置' }}秒</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">QPS限制：</span>
              <span class="config-value">{{ configDialogData.taskConfig.qps_limit || '无限制' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 环境配置 -->
      <el-card class="config-section" shadow="never" v-if="configDialogData.taskConfig.environment">
        <template #header>
          <div class="config-section-title">
            <el-icon><Monitor /></el-icon>
            环境配置
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">环境名称：</span>
              <span class="config-value">{{ configDialogData.taskConfig.environment.name || '默认环境' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">基础URL：</span>
              <span class="config-value">{{ configDialogData.taskConfig.environment.base_url || configDialogData.taskConfig.environment.host || '未设置' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">协议：</span>
              <span class="config-value">{{ configDialogData.taskConfig.environment.protocol || 'HTTP' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="config-label">超时设置：</span>
              <span class="config-value">{{ configDialogData.taskConfig.environment.timeout || configDialogData.taskConfig.timeout || '30' }}秒</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </el-dialog>

  <!-- 通知配置对话框 -->
  <el-dialog 
    v-model="notificationDialogData.visible" 
    title="测试报告推送" 
    width="680px" 
    custom-class="modern-notification-dialog" 
    :required="true" 
    :before-close="cancelNotification"
    top="5vh"
    center
    append-to-body
    destroy-on-close
  >
    <div class="notification-dialog-content">
      <div class="notification-dialog-header">
        <div class="notification-title">
          <el-icon class="notification-icon"><Bell /></el-icon>
          <span>分享测试报告结果</span>
        </div>
        <div class="notification-subtitle">选择通知方式，将测试结果分享给团队成员</div>
      </div>
      
      <el-form :model="notificationDialogData" :rules="notificationRules" ref="notificationFormRef" label-position="top" class="notification-form">
        <el-form-item prop="name" label="通知标题">
          <el-input 
            v-model="notificationDialogData.name" 
            maxlength="50" 
            minlength="1" 
            placeholder="例如：性能测试报告 - 系统优化后结果"
            class="notification-input"
          />
      </el-form-item>
      
        <el-form-item prop="pushType" label="选择通知方式">
          <div class="notification-type-selector">
          <div 
              class="notification-type-option" 
              :class="{ 'selected': notificationDialogData.pushType === 'email' }"
            @click="notificationDialogData.pushType = 'email'"
          >
              <div class="option-icon email-icon"><el-icon><Message /></el-icon></div>
              <span>邮件</span>
          </div>
            
          <div 
              class="notification-type-option" 
              :class="{ 'selected': notificationDialogData.pushType === 'webhook' }"
            @click="notificationDialogData.pushType = 'webhook'"
          >
              <div class="option-icon webhook-icon"><el-icon><Link /></el-icon></div>
              <span>Webhook</span>
          </div>
            
          <div 
              class="notification-type-option" 
              :class="{ 'selected': notificationDialogData.pushType === 'dingtalk' }"
            @click="notificationDialogData.pushType = 'dingtalk'"
          >
              <div class="option-icon dingtalk-icon"><el-icon><ChatDotRound /></el-icon></div>
              <span>钉钉</span>
          </div>
            
          <div 
              class="notification-type-option" 
              :class="{ 'selected': notificationDialogData.pushType === 'wechat' }"
            @click="notificationDialogData.pushType = 'wechat'"
          >
              <div class="option-icon wechat-icon"><el-icon><ChatRound /></el-icon></div>
              <span>微信</span>
          </div>
        </div>
      </el-form-item>
      
        <el-form-item prop="webhook" label="推送地址" v-if="notificationDialogData.pushType && notificationDialogData.pushType !== 'email'">
          <el-input 
            v-model="notificationDialogData.webhook" 
            minlength="3" 
            placeholder="请输入webhook地址" 
            class="notification-input"
          >
          <template #prefix>
            <el-icon v-if="notificationDialogData.pushType === 'webhook'"><Link /></el-icon>
            <el-icon v-if="notificationDialogData.pushType === 'dingtalk'"><ChatDotRound /></el-icon>
            <el-icon v-if="notificationDialogData.pushType === 'wechat'"><ChatRound /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      
      <el-form-item prop="recipients" label="接收人" v-if="notificationDialogData.pushType === 'email'">
          <el-select 
            multiple 
            v-model="notificationDialogData.recipients" 
            placeholder="请选择接收人" 
            style="width: 100%;" 
            collapse-tags 
            collapse-tags-tooltip
            class="notification-select"
          >
          <el-option :label="'@all'" :value="'@all'" :key="'@all'" :disabled="notificationDialogData.recipients.length > 0 && !notificationDialogData.recipients.includes('@all')"></el-option>
          <el-option 
            label="admin@example.com" 
            value="admin@example.com" 
            :disabled="notificationDialogData.recipients.includes('@all')"
          ></el-option>
        </el-select>
          <div class="notification-tip">选择 @all 将通知所有人，与其他接收人互斥</div>
      </el-form-item>

        <div class="notification-report-preview">
          <div class="preview-header">
            <el-icon><Document /></el-icon>
            <span>报告摘要</span>
          </div>
          <div class="preview-content">
            <div class="preview-item">
              <span class="item-label">报告名称:</span>
              <span class="item-value">{{ reportData.reportName }}</span>
            </div>
            <div class="preview-item">
              <span class="item-label">测试状态:</span>
              <span class="item-value">
                <el-button :type="reportData.reportStatus === '0' ? 'success' : 'info'" size="small">
              {{ getStatusText(reportData.reportStatus) }}
                </el-button>
              </span>
        </div>
            <div class="metrics-section">
              <div class="metrics-row">
                <div class="metric-item-wide">
                  <div class="metric-label">响应时间</div>
                  <div class="metric-value">{{ formatResponseTime(reportData.avgResponseTime) }}</div>
                </div>
                <div class="metric-item-wide">
                  <div class="metric-label">成功率</div>
                  <div class="metric-value">{{ getSuccessRate() }}%</div>
                </div>
              </div>
              <div class="metrics-row">
                <div class="metric-item-wide">
                  <div class="metric-label">平均TPS</div>
                  <div class="metric-value">{{ (reportData.avgTps || 0).toFixed(2) }}</div>
                </div>
                <div class="metric-item-wide">
                  <div class="metric-label">并发用户</div>
                  <div class="metric-value">{{ reportData.maxUsers || reportData.avgUsers || '未设置' }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
    </el-form>
    </div>
    
    <template #footer>
      <div class="notification-dialog-footer">
        <el-button @click="cancelNotification" plain>取消</el-button>
        <el-button type="primary" @click="confirmSendNotification">
          <el-icon><Position /></el-icon> 发送通知
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 创建基准线对话框 -->
  <el-dialog
    v-model="baselineDialogData.visible"
    :title="'创建性能基准线'"
    width="600px"
    destroy-on-close>
    
    <el-form :model="baselineDialogData.form" :rules="baselineFormRules" ref="baselineFormRef" label-width="120px">
      <el-form-item label="基准线名称" prop="name">
        <el-input v-model="baselineDialogData.form.name" placeholder="请输入基准线名称"></el-input>
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="baselineDialogData.form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入基准线描述">
        </el-input>
      </el-form-item>
      
      <el-divider content-position="center">性能指标</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="响应时间(ms)" prop="avg_response_time">
            <el-input-number
              v-model="baselineDialogData.form.avg_response_time"
              :precision="2"
              :min="0"
              style="width: 100%">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="TPS" prop="avg_tps">
            <el-input-number
              v-model="baselineDialogData.form.avg_tps"
              :precision="2"
              :min="0"
              style="width: 100%">
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="成功率(%)" prop="success_rate">
            <el-input-number
              v-model="baselineDialogData.form.success_rate"
              :precision="2"
              :min="0"
              :max="100"
              style="width: 100%">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="CPU使用率(%)" prop="avg_cpu">
            <el-input-number
              v-model="baselineDialogData.form.avg_cpu"
              :precision="2"
              :min="0"
              :max="100"
              style="width: 100%">
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="内存使用率(%)" prop="avg_memory">
            <el-input-number
              v-model="baselineDialogData.form.avg_memory"
              :precision="2"
              :min="0"
              :max="100"
              style="width: 100%">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否激活">
            <el-switch v-model="baselineDialogData.form.is_active"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      
      <div class="baseline-info-hint">
        <el-icon><InfoFilled /></el-icon>
        <span>这些性能指标将作为未来性能测试的参考基准</span>
      </div>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="baselineDialogData.visible = false">取消</el-button>
        <el-button type="primary" @click="submitBaselineForm" :loading="baselineDialogData.loading">创建</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 基准线选择对话框 -->
  <el-dialog
    v-model="baselineCompareDialogData.visible"
    title="选择要对比的基准线"
    width="500px"
    destroy-on-close>
    
    <el-form label-width="100px">
      <el-form-item label="基准线">
        <el-select v-model="baselineCompareDialogData.selectedBaselineId" style="width: 100%">
          <el-option
            v-for="baseline in baselineCompareDialogData.baselineList"
            :key="baseline.id"
            :label="baseline.name"
            :value="baseline.id">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span>{{ baseline.name }}</span>
              <span style="font-size: 12px; color: #999">{{ formatTime(baseline.create_time) }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="baselineCompareDialogData.visible = false">取消</el-button>
        <el-button type="primary" @click="submitCompareBaseline" :loading="baselineCompareDialogData.loading">开始对比</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 基准线对比结果对话框 -->
  <el-dialog
    v-model="baselineCompareResultData.visible"
    title="性能基准线对比结果"
    width="800px"
    destroy-on-close>
    
    <div class="comparison-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="comparison-card baseline">
            <div class="comparison-header">
              <el-icon><TrendCharts /></el-icon>
              <span>基准线</span>
            </div>
            <div class="comparison-metrics">
              <div class="metric-row">
                <span class="metric-label">响应时间:</span>
                <span class="metric-value">{{ baselineCompareResultData.baseline_metrics.avg_response_time.toFixed(2) }}ms</span>
              </div>
              <div class="metric-row">
                <span class="metric-label">TPS:</span>
                <span class="metric-value">{{ baselineCompareResultData.baseline_metrics.avg_tps.toFixed(2) }}</span>
              </div>
              <div class="metric-row">
                <span class="metric-label">成功率:</span>
                <span class="metric-value">{{ baselineCompareResultData.baseline_metrics.success_rate.toFixed(2) }}%</span>
              </div>
              <div class="metric-row">
                <span class="metric-label">CPU使用率:</span>
                <span class="metric-value">{{ baselineCompareResultData.baseline_metrics.avg_cpu?.toFixed(2) || '0.00' }}%</span>
              </div>
              <div class="metric-row">
                <span class="metric-label">内存使用率:</span>
                <span class="metric-value">{{ baselineCompareResultData.baseline_metrics.avg_memory?.toFixed(2) || '0.00' }}%</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="comparison-card current">
            <div class="comparison-header">
              <el-icon><Document /></el-icon>
              <span>当前报告</span>
            </div>
            <div class="comparison-metrics">
              <div class="metric-row">
                <span class="metric-label">响应时间:</span>
                <span class="metric-value">{{ baselineCompareResultData.current_metrics.avg_response_time.toFixed(2) }}ms</span>
                <span :class="getComparisonClass(
                  baselineCompareResultData.current_metrics.avg_response_time,
                  baselineCompareResultData.baseline_metrics.avg_response_time,
                  'response_time'
                )">
                  {{ getComparisonText(
                    baselineCompareResultData.current_metrics.avg_response_time,
                    baselineCompareResultData.baseline_metrics.avg_response_time,
                    'response_time'
                  ) }}
                </span>
              </div>
              <div class="metric-row">
                <span class="metric-label">TPS:</span>
                <span class="metric-value">{{ baselineCompareResultData.current_metrics.avg_tps.toFixed(2) }}</span>
                <span :class="getComparisonClass(
                  baselineCompareResultData.current_metrics.avg_tps,
                  baselineCompareResultData.baseline_metrics.avg_tps,
                  'tps'
                )">
                  {{ getComparisonText(
                    baselineCompareResultData.current_metrics.avg_tps,
                    baselineCompareResultData.baseline_metrics.avg_tps,
                    'tps'
                  ) }}
                </span>
              </div>
              <div class="metric-row">
                <span class="metric-label">成功率:</span>
                <span class="metric-value">{{ baselineCompareResultData.current_metrics.success_rate.toFixed(2) }}%</span>
                <span :class="getComparisonClass(
                  baselineCompareResultData.current_metrics.success_rate,
                  baselineCompareResultData.baseline_metrics.success_rate,
                  'success_rate'
                )">
                  {{ getComparisonText(
                    baselineCompareResultData.current_metrics.success_rate,
                    baselineCompareResultData.baseline_metrics.success_rate,
                    'success_rate'
                  ) }}
                </span>
              </div>
              <div class="metric-row">
                <span class="metric-label">CPU使用率:</span>
                <span class="metric-value">{{ baselineCompareResultData.current_metrics.avg_cpu?.toFixed(2) || '0.00' }}%</span>
                <span :class="getComparisonClass(
                  baselineCompareResultData.current_metrics.avg_cpu || 0,
                  baselineCompareResultData.baseline_metrics.avg_cpu || 0,
                  'cpu'
                )">
                  {{ getComparisonText(
                    baselineCompareResultData.current_metrics.avg_cpu || 0,
                    baselineCompareResultData.baseline_metrics.avg_cpu || 0,
                    'cpu'
                  ) }}
                </span>
              </div>
              <div class="metric-row">
                <span class="metric-label">内存使用率:</span>
                <span class="metric-value">{{ baselineCompareResultData.current_metrics.avg_memory?.toFixed(2) || '0.00' }}%</span>
                <span :class="getComparisonClass(
                  baselineCompareResultData.current_metrics.avg_memory || 0,
                  baselineCompareResultData.baseline_metrics.avg_memory || 0,
                  'memory'
                )">
                  {{ getComparisonText(
                    baselineCompareResultData.current_metrics.avg_memory || 0,
                    baselineCompareResultData.baseline_metrics.avg_memory || 0,
                    'memory'
                  ) }}
                </span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 对比结论 -->
      <div class="comparison-conclusion">
        <div class="conclusion-header">
          <el-icon><InfoFilled /></el-icon>
          <span>对比结论</span>
        </div>
        <div class="conclusion-content">
          <p v-if="baselineCompareResultData.conclusion">{{ baselineCompareResultData.conclusion }}</p>
          <p v-else>{{ generateComparisonConclusion() }}</p>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="baselineCompareResultData.visible = false">关闭</el-button>
        <el-button type="primary" @click="exportComparisonResult">导出对比报告</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { Icon } from '@iconify/vue'
import ResponseTimeChart from '@/components/echart/ResponseTimeChart.vue'
import {
  Edit,
  View,
  SwitchButton,
  InfoFilled,
  TrendCharts,
  Search,
  ArrowDown,
  ArrowLeft,
  Check,
  Download,
  Document,
  Monitor,
  DocumentCopy,
  Files,
  Bell,
  Message,
  Link,
  ChatDotRound,
  ChatRound,
  MoreFilled,
  DataAnalysis,
  PieChart,
  Setting,
  // 添加新的图标组件
  Connection,
  CircleClose
} from '@element-plus/icons-vue'

export default {
  name: 'PerformanceResult-Detail',
  components: {
    Icon,
    ResponseTimeChart,
    Edit,
    View,
    SwitchButton,
    InfoFilled,
    TrendCharts,
    Search,
    ArrowDown,
    ArrowLeft,
    Check,
    Download,
    Document,
    Monitor,
    DocumentCopy,
    Files,
    Bell,
    Message,
    Link,
    ChatDotRound,
    ChatRound,
    MoreFilled,
    DataAnalysis,
    PieChart,
    Setting,
    // 添加新的图标组件
    Connection,
    CircleClose
  },
  data() {
    return {
      reportId: null,
      selectedKeys: [],
      reportData: {},
      taskName: '',
      desc: '',
      taskType: '',
      inputDlg: false,
      editingField: '',
      tempTaskName: '', // 用于编辑任务名称时的临时存储
      activeIndex: '1',
      textResult: '',
      reportList: [],
      xData: [],
      seriesData: [],
      realTimeData: {},
      monitoringData: {},
      logData: [],
      // 基准线对话框数据
      baselineDialogData: {
        visible: false,
        loading: false,
        mode: 'create',
        form: {
          name: '',
          description: '',
          task_id: null,
          avg_response_time: 0,
          avg_tps: 0,
          success_rate: 0,
          avg_cpu: 0,
          avg_memory: 0,
          is_active: true,
          project_id: null
        }
      },
      // 基准线表单验证规则
      baselineFormRules: {
        name: [
          { required: true, message: '请输入基准线名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur' }
        ],
        task_id: [
          { required: true, message: '请选择关联任务', trigger: 'change' }
        ]
      },
      // 基准线对比对话框数据
      baselineCompareDialogData: {
        visible: false,
        loading: false,
        baselineList: [],
        selectedBaselineId: null
      },
      // 基准线对比结果数据
      baselineCompareResultData: {
        visible: false,
        baseline_metrics: {
          avg_response_time: 0,
          avg_tps: 0,
          success_rate: 0,
          avg_cpu: 0,
          avg_memory: 0
        },
        current_metrics: {
          avg_response_time: 0,
          avg_tps: 0,
          success_rate: 0,
          avg_cpu: 0,
          avg_memory: 0
        },
        conclusion: ''
      },
      // 添加新的日志相关数据
      logCategories: {
        all: '全部',
        system: '系统',
        request: '请求',
        error: '错误',
        performance: '性能',
        event: '事件'
      },
      logCategory: 'all',
      // WebSocket相关数据
      wsConnection: null,
      wsReconnectAttempts: 0,
      wsMaxReconnectAttempts: 5,
      wsReconnectInterval: null,
      wsConnectionStatus: 'disconnected', // disconnected, connecting, connected, error
      autoRefresh: true,
      refreshInterval: null,
      // 添加缺失的数据属性
      targetServiceData: {},
      logFilter: '',
      logLevel: 'all',
      tableLoading: false, // 添加loading状态
      chartUpdateKey: 0, // 用于强制更新图表
      // 监控数据加载标志
      monitoringDataLoaded: false,
      targetServiceDataLoaded: false,
      logDataLoaded: false,
      // 监控数据刷新定时器
      monitoringRefreshInterval: null,
      targetServiceRefreshInterval: null,
      // 分离的图表数据
      responseTimeData: [],
      rpsData: [],
      tpsData: [],
      usersData: [],
      p50Data: [], // 添加p50数据数组
      p90Data: [],
      p95Data: [], // 添加p95数据数组
      p99Data: [],
      errorRateData: [],
      // 多接口图表数据
      interfaceChartData: {
        responseTime: {},
        rps: {},
        tps: {},
        users: {},
        p50: {}, // 添加p50接口数据
        p90: {},
        p95: {}, // 添加p95接口数据
        p99: {},
        errorRate: {}
      },
      availableInterfaces: [], // 可用的接口列表
      realTimeUpdateInterval: null, // 实时更新定时器
      // 仅查看功能相关数据
      isFilterMode: false, // 是否处于筛选模式
      selectedRows: [], // 选中的行数据
      // GUI相关数据
      guiUrl: '',  // 由后端提供的完整GUI URL
      hasGuiUrlLoaded: false,
      iframeError: false,
      iframeErrorMessage: '',

      // 对话框数据
      analysisDialogData: {
        visible: false,
        performance_score: 0,
        bottlenecks: [],
        recommendations: []
      },
      configDialogData: {
        visible: false,
        taskConfig: null
      },
      notificationDialogData: {
        visible: false,
        type: '',
        pushType: 'wechat',
        name: '',
        webhook: '',
        recipients: [],
      },
      // 添加验证规则
      notificationRules: {
        name: [
          { required: true, message: '请输入推送名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        pushType: [
          { required: true, message: '请选择推送类型', trigger: 'change' }
        ],
        webhook: [
          { required: true, message: '请输入webhook地址', trigger: 'blur' },
          { min: 3, message: 'webhook地址至少3个字符', trigger: 'blur' }
        ],
        recipients: [
          { required: true, message: '请选择接收人', trigger: 'change' }
        ]
      },
      monitorUrl: '', // 新增：输入框内容
      monitorIframeUrl: '', // 新增：iframe展示url
    }
  },
  computed: {
    // 测试是否正在运行
    isTestRunning() {
      return this.reportData.reportStatus === '1' || this.taskType === '运行中';
    },

    isEdit(){
      return true  // 始终允许编辑结果分析
    },
    // 过滤日志
    filteredLogs() {
      let logs = this.logData

      // 按日志级别过滤
      if (this.logLevel && this.logLevel !== 'all') {
        logs = logs.filter(log => log.level === this.logLevel)
      }

      // 按日志类别过滤
      if (this.logCategory && this.logCategory !== 'all') {
        logs = logs.filter(log => log.category === this.logCategory)
      }

      // 按关键词过滤
      if (this.logFilter) {
        logs = logs.filter(log =>
          log.message.toLowerCase().includes(this.logFilter.toLowerCase()) ||
          (log.details && log.details.toLowerCase().includes(this.logFilter.toLowerCase()))
        )
      }

      // 按时间正序排列，旧的在上面，新的在下面
      return logs.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
    },

    // 响应时间图表数据
    responseTimeSeriesData() {
      const seriesData = [];
      if (this.isFilterMode && this.selectedRows.length > 0) {
        this.selectedKeys = this.selectedRows.map(row => row.method + '_' + row.name);
      }Object.keys(this.interfaceChartData.responseTime).forEach(interfaceKey => {
        if (this.isFilterMode && this.selectedKeys && !this.selectedKeys.includes(interfaceKey)) {
          return;
        }
        if (this.interfaceChartData.responseTime[interfaceKey].length > 0) {
          seriesData.push({
            name: interfaceKey,
            values: this.interfaceChartData.responseTime[interfaceKey]
          });
        }
      });
      return seriesData.length > 0 ? seriesData : [{ name: '平均响应时间', values: [] }];
    },

    // RPS图表数据
    rpsSeriesData() {
      const seriesData = [];
      if (this.isFilterMode && this.selectedRows.length > 0) {
        this.selectedKeys = this.selectedRows.map(row => row.method + '_' + row.name);
      }

      Object.keys(this.interfaceChartData.rps).forEach(interfaceKey => {
        if (this.isFilterMode && this.selectedKeys && !this.selectedKeys.includes(interfaceKey)) {
          return;
        }
        if (this.interfaceChartData.rps[interfaceKey].length > 0) {
          seriesData.push({
            name: interfaceKey,
            values: this.interfaceChartData.rps[interfaceKey]
          });
        }
      });
      if (seriesData.length === 0 && this.rpsData && this.rpsData.length > 0) {
        seriesData.push({
          name: '总体RPS',
          values: this.rpsData
        });
      }
      return seriesData.length > 0 ? seriesData : [{ name: 'RPS', values: [] }];
    },

    // TPS图表数据
    tpsSeriesData() {
      const seriesData = [];
      if (this.isFilterMode && this.selectedRows.length > 0) {
        this.selectedKeys = this.selectedRows.map(row => row.method + '_' + row.name);
      }
      Object.keys(this.interfaceChartData.tps).forEach(interfaceKey => {
        if (this.isFilterMode && this.selectedKeys && !this.selectedKeys.includes(interfaceKey)) {
          return;
        }
        if (this.interfaceChartData.tps[interfaceKey].length > 0) {
          seriesData.push({
            name: interfaceKey,
            values: this.interfaceChartData.tps[interfaceKey]
          });
        }
      });
      if (seriesData.length === 0 && this.tpsData && this.tpsData.length > 0) {
        seriesData.push({
          name: '总体TPS',
          values: this.tpsData
        });
      }
      return seriesData.length > 0 ? seriesData : [{ name: 'TPS', values: [] }];
    },

    // 用户数图表数据
    usersSeriesData() {
      const seriesData = [];
      // 用户数只显示总体数据（因为用户数是全局的）
      if (this.usersData.length > 0) {
        seriesData.push({
          name: '并发用户数',
          values: this.usersData
        });
      }
      return seriesData.length > 0 ? seriesData : [{ name: '并发用户数', values: [] }];
    },

    // P50响应时间图表数据
    p50SeriesData() {
      const seriesData = [];
      if (this.isFilterMode && this.selectedRows.length > 0) {
        this.selectedKeys = this.selectedRows.map(row => row.method + '_' + row.name);
      }
      Object.keys(this.interfaceChartData.p50).forEach(interfaceKey => {
        if (this.isFilterMode && this.selectedKeys && !this.selectedKeys.includes(interfaceKey)) {
          return;
        }
        if (this.interfaceChartData.p50[interfaceKey].length > 0) {
          seriesData.push({
            name: interfaceKey,
            values: this.interfaceChartData.p50[interfaceKey]
          });
        }
      });
      return seriesData.length > 0 ? seriesData : [{ name: '50%响应时间线', values: [] }];
    },

    // P90响应时间图表数据
    p90SeriesData() {
      const seriesData = [];
      if (this.isFilterMode && this.selectedRows.length > 0) {
        this.selectedKeys = this.selectedRows.map(row => row.method + '_' + row.name);
      }
      Object.keys(this.interfaceChartData.p90).forEach(interfaceKey => {if (this.isFilterMode && this.selectedKeys && !this.selectedKeys.includes(interfaceKey)) {
          return;
        }
        if (this.interfaceChartData.p90[interfaceKey].length > 0) {
          seriesData.push({
            name: interfaceKey,
            values: this.interfaceChartData.p90[interfaceKey]
          });
        }
      });
      return seriesData.length > 0 ? seriesData : [{ name: '90%响应时间线', values: [] }];
    },

    // P95响应时间图表数据
    p95SeriesData() {
      const seriesData = [];
      if (this.isFilterMode && this.selectedRows.length > 0) {
        this.selectedKeys = this.selectedRows.map(row => row.method + '_' + row.name);
      }
      Object.keys(this.interfaceChartData.p95).forEach(interfaceKey => {
        if (this.isFilterMode && this.selectedKeys && !this.selectedKeys.includes(interfaceKey)) {
          return;
        }
        if (this.interfaceChartData.p95[interfaceKey].length > 0) {
          seriesData.push({
            name: interfaceKey,
            values: this.interfaceChartData.p95[interfaceKey]
          });
        }
      });
      return seriesData.length > 0 ? seriesData : [{ name: '95%响应时间线', values: [] }];
    },

    // P99响应时间图表数据
    p99SeriesData() {
      const seriesData = [];
      if (this.isFilterMode && this.selectedRows.length > 0) {
        this.selectedKeys = this.selectedRows.map(row => row.method + '_' + row.name);
      }
      Object.keys(this.interfaceChartData.p99).forEach(interfaceKey => {
        if (this.isFilterMode && this.selectedKeys && !this.selectedKeys.includes(interfaceKey)) {
          return;
        }
        if (this.interfaceChartData.p99[interfaceKey].length > 0) {
          seriesData.push({
            name: interfaceKey,
            values: this.interfaceChartData.p99[interfaceKey]
          });
        }
      });
      return seriesData.length > 0 ? seriesData : [{ name: '99%响应时间线', values: [] }];
    },

    // 筛选后的指标数据
    filteredMetrics() {
      const allMetrics = this.getDetailedMetrics();

      if (!this.isFilterMode || this.selectedRows.length === 0) {
        // 如果不在筛选模式或没有选中任何行，返回所有数据
        return allMetrics;
      }

      // 获取选中行的接口名称
      const selectedNames = this.selectedRows.map(row => row.name);

      // 保留总体数据和选中的接口数据
      const filteredData = allMetrics.filter(metric =>
        metric.method === 'ALL' || selectedNames.includes(metric.name)
      );
      
      // 确保总体数据始终显示在第一行
      const totalData = filteredData.filter(metric => metric.method === 'ALL');
      const detailData = filteredData.filter(metric => metric.method !== 'ALL');
      
      return [...totalData, ...detailData];
    }
  },

  methods: {
    // 获取成功率
    getSuccessRate() {
      if (!this.reportData || !this.reportData.totalRequests || this.reportData.totalRequests <= 0) {
        return 0;
      }
      const successRequests = this.reportData.successRequests || 0;
      return Math.round((successRequests / this.reportData.totalRequests) * 100);
    },

    // 停止性能测试
    async stopPerformanceTest() {
      if (!this.reportData.task?.id && !this.reportData.taskId) {
        this.$message.error('无法获取任务ID');
        return;
      }
      const taskId = this.reportData.task?.id || this.reportData.taskId;
      try {
        await this.$confirm('确定要暂停/终止当前性能测试吗？', '暂停运行', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        this.tableLoading = true;
        const response = await this.$api.stopPerformanceTest(taskId);
        this.$message.success('性能测试已暂停/终止');
        // 更新状态
        this.taskType = '运行失败';
        this.reportData.reportStatus = '99';
        this.stopAllRealTimeUpdates();
        await this.loadReportData();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('暂停失败: ' + (error.response?.data?.message || error.message || '未知错误'));
        }
      } finally {
        this.tableLoading = false;
      }
    },

    // 初始化WebSocket连接
    initWebSocket() {
      // 清理现有连接
      this.cleanupWebSocket()

      // 检查是否需要WebSocket连接
      if (!this.reportId || this.reportData.reportStatus !== '1') {
        return
      }

      this.wsConnectionStatus = 'connecting'

      try {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        const baseUrl = process.env.VUE_APP_WS_BASE_URL || window.location.host
        const wsUrl = `${protocol}//${baseUrl}/ws/performance/report/${this.reportId}/`

        this.wsConnection = new WebSocket(wsUrl)

        // 设置连接超时
        const connectionTimeout = setTimeout(() => {
          if (this.wsConnection && this.wsConnection.readyState === WebSocket.CONNECTING) {
            this.wsConnection.close()
            this.handleWebSocketError('连接超时')
          }
        }, 10000) // 10秒超时

        this.wsConnection.onopen = () => {
          clearTimeout(connectionTimeout)
          this.wsConnectionStatus = 'connected'
          this.wsReconnectAttempts = 0

          // 发送心跳检测
          this.startHeartbeat()

          this.$message.success('实时监控已启动')
        }

        this.wsConnection.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data)
            this.handleWebSocketMessage(data)
          } catch (error) {
            console.error('解析WebSocket消息失败:', error)
          }
        }

        this.wsConnection.onerror = (error) => {
          clearTimeout(connectionTimeout)
          console.error('WebSocket连接错误:', error)
          this.handleWebSocketError('连接错误')
        }

        this.wsConnection.onclose = (event) => {
          clearTimeout(connectionTimeout)
          this.wsConnectionStatus = 'disconnected'
          this.stopHeartbeat()

          // 判断是否需要重连
          if (this.shouldReconnect(event)) {
            this.attemptReconnect()
          }
        }
      } catch (error) {
        this.handleWebSocketError('创建连接失败')
      }
    },

    // 清理WebSocket连接
    cleanupWebSocket() {
      if (this.wsConnection) {
        this.wsConnection.close()
        this.wsConnection = null
      }
      this.stopHeartbeat()
      this.clearReconnectTimer()
      this.wsConnectionStatus = 'disconnected'
    },

    // 判断是否应该重连
    shouldReconnect(event) {
      // 正常关闭不重连
      if (event.code === 1000) {
        return false
      }

      // 测试已完成不重连
      if (this.reportData.reportStatus !== '1') {
        return false
      }

      // 超过最大重连次数不重连
      if (this.wsReconnectAttempts >= this.wsMaxReconnectAttempts) {
        this.$message.warning('实时监控连接已断开，请手动刷新页面')
        return false
      }

      // 用户关闭了自动刷新不重连
      if (!this.autoRefresh) {
        return false
      }

      return true
    },

    // 尝试重连
    attemptReconnect() {
      this.wsReconnectAttempts++
      const delay = Math.min(1000 * Math.pow(2, this.wsReconnectAttempts), 30000) // 指数退避，最大30秒

      console.log(`尝试第${this.wsReconnectAttempts}次重连，${delay}ms后重试`)

      this.wsReconnectInterval = setTimeout(() => {
        if (this.wsConnectionStatus !== 'connected') {
          this.initWebSocket()
        }
      }, delay)
    },

    // 清理重连定时器
    clearReconnectTimer() {
      if (this.wsReconnectInterval) {
        clearTimeout(this.wsReconnectInterval)
        this.wsReconnectInterval = null
      }
    },

    // 处理WebSocket错误
    handleWebSocketError(errorMessage) {
      this.wsConnectionStatus = 'error'
      console.error('WebSocket错误:', errorMessage)

      // 如果是首次连接失败，提示用户
      if (this.wsReconnectAttempts === 0) {
        // 启用定时刷新作为备用方案
        this.enablePollingMode()
      }
    },

    // 启用轮询模式作为WebSocket的备用方案
    enablePollingMode() {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval)
      }

      if (this.autoRefresh && this.reportData.reportStatus === '1') {
        this.refreshInterval = setInterval(() => {
          this.loadMonitoringData()
          this.loadTargetServiceData()
          this.loadLogData()
        }, 5000) // 每5秒刷新一次

      }
    },

    // 心跳检测
    startHeartbeat() {
      this.heartbeatInterval = setInterval(() => {
        if (this.wsConnection && this.wsConnection.readyState === WebSocket.OPEN) {
          this.wsConnection.send(JSON.stringify({ type: 'heartbeat' }))
        }
      }, 30000) // 每30秒发送一次心跳
    },

    // 停止心跳检测
    stopHeartbeat() {
      if (this.heartbeatInterval) {
        clearInterval(this.heartbeatInterval)
        this.heartbeatInterval = null
      }
    },

    // 手动重连WebSocket
    reconnectWebSocket() {
      this.wsReconnectAttempts = 0
      this.initWebSocket()
    },

    // 处理WebSocket消息
    handleWebSocketMessage(data) {

      if (data.type === 'performance_update') {
        // 处理性能更新数据
        this.realTimeData = data.data;
        this.updateChartData();

        // 更新实时指标显示
        if (data.data && data.data.total) {
          const total = data.data.total;

          // 更新报告基础数据的实时指标
          this.updateBasicMetricsFromWebSocket(total);

          
          // 添加性能指标日志
          this.addPerformanceLog({
            tps: total.current_rps,
            responseTime: total.avg_response_time,
            users: total.current_users,
            errorRate: total.error_rate
          });
        }

        // 如果有详细统计数据，也更新到指标详情表格
        if (data.data && data.data.detailed_stats) {
          // 强制触发表格数据更新
          this.$nextTick(() => {
            this.$forceUpdate();
          });
        }

      } else if (data.type === 'log_update') {
        // 处理日志更新 - 增强日志处理
        const logData = this.enhanceLogData(data.data);
        this.logData.push(logData);
        // 保持最新2000条日志
        if (this.logData.length > 2000) {
          this.logData = this.logData.slice(-2000);
        }
        
        this.scrollToLogBottom();

      } else if (data.type === 'monitoring_update' || data.type === 'system_resources') {
        // 处理系统资源监控更新
        this.monitoringData = data.data;
        
        // 添加系统资源日志
        this.addSystemResourceLog(data.data);
        
        // 强制更新系统资源卡片显示
        this.$forceUpdate();

      } else if (data.type === 'test_complete') {
        
        // 添加测试完成事件日志
        this.addEventLog('测试完成', '收到测试完成信号，正在验证测试状态...', 'info');

        // 延迟验证，给测试更多时间完成清理工作
        setTimeout(() => {
          this.verifyTestCompletion();
        }, 3000); // 延长到3秒

      } else if (data.type === 'test_failed') {
        // 处理测试失败
        this.taskType = '运行失败';
        this.reportData.reportStatus = '99';
        
        // 添加测试失败事件日志
        this.addEventLog('测试失败', '测试执行失败，请检查详细错误信息', 'error');

        // 停止所有实时数据更新
        this.stopAllRealTimeUpdates();
      } else if (data.type === 'request_success' || data.type === 'request_failure') {
        // 处理请求成功/失败事件
        this.addRequestLog(data);
      }
    },
    
    // 增强日志数据
    enhanceLogData(logData) {
      // 如果日志数据已经包含category，直接返回
      if (logData.category) {
        return logData;
      }
      
      // 根据日志内容推断类别
      let category = 'system'; // 默认为系统日志
      
      const message = logData.message || '';
      if (message.includes('ERROR') || message.includes('Exception') || logData.level === 'error') {
        category = 'error';
      } else if (message.includes('Request') || message.includes('HTTP') || message.includes('GET ') || 
                message.includes('POST ') || message.includes('PUT ') || message.includes('DELETE ')) {
        category = 'request';
      } else if (message.includes('TPS') || message.includes('RPS') || message.includes('响应时间') || 
                message.includes('用户数') || message.includes('性能')) {
        category = 'performance';
      } else if (message.includes('开始') || message.includes('结束') || message.includes('启动') || 
                message.includes('停止') || message.includes('完成')) {
        category = 'event';
      }
      
      // 添加详细信息字段
      let details = '';
      if (message.includes('{') && message.includes('}')) {
        try {
          // 尝试提取JSON格式的详细信息
          const jsonStart = message.indexOf('{');
          const jsonEnd = message.lastIndexOf('}') + 1;
          const jsonStr = message.substring(jsonStart, jsonEnd);
          const jsonData = JSON.parse(jsonStr);
          details = JSON.stringify(jsonData, null, 2);
        } catch (e) {
          // 提取失败，忽略错误
        }
      }
      
      return {
        ...logData,
        category,
        details,
        formatted: this.formatLogMessage(logData)
      };
    },
    
    // 格式化日志消息
    formatLogMessage(log) {
      const message = log.message || '';
      
      // 格式化请求日志
      if (message.includes('HTTP') && (message.includes('GET') || message.includes('POST') || 
          message.includes('PUT') || message.includes('DELETE'))) {
        // 提取HTTP方法、URL和状态码
        const methodMatch = message.match(/(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s+([^\s]+)/);
        const statusMatch = message.match(/status\s+(\d+)/i) || message.match(/(\d{3})/);
        
        if (methodMatch) {
          const method = methodMatch[1];
          const url = methodMatch[2];
          const status = statusMatch ? statusMatch[1] : '';
          
          return {
            method,
            url,
            status,
            isFormatted: true
          };
        }
      }
      
      return null;
    },
    
    // 滚动到日志底部的辅助方法
    scrollToLogBottom() {
      // 如果在日志标签页，自动滚动到底部
      if (this.activeIndex === '5') {
        this.$nextTick(() => {
          const logContainer = document.querySelector('.log-container');
          if (logContainer) {
            logContainer.scrollTop = logContainer.scrollHeight;
          }
        });
      }
    },

    // 添加系统资源日志
    addSystemResourceLog(data) {
      if (!data) return;
      
      // 每分钟只记录一次系统资源日志，避免日志过多
      const now = new Date();
      const lastSystemLog = this.logData.find(log => log.category === 'system' && log.type === 'resource');
      if (lastSystemLog) {
        const lastTime = new Date(lastSystemLog.timestamp);
        if (now - lastTime < 60000) { // 小于1分钟不记录
          return;
        }
      }
      
      this.logData.push({
        timestamp: new Date().toISOString(),
        level: 'info',
        category: 'system',
        type: 'resource',
        message: `系统资源: CPU ${data.cpu_percent || 0}%, 内存 ${data.memory_percent || 0}%, 磁盘 ${data.disk_percent || 0}%`,
        details: JSON.stringify({
          cpu: data.cpu_percent || 0,
          memory: data.memory_percent || 0,
          disk: data.disk_percent || 0,
          network_sent: this.formatBytes(data.network_sent || 0),
          network_recv: this.formatBytes(data.network_recv || 0)
        }, null, 2)
      });
      
      // 保持最新2000条日志
      if (this.logData.length > 2000) {
        this.logData = this.logData.slice(-2000);
      }
      
      this.scrollToLogBottom();
    },
    
    // 添加性能指标日志
    addPerformanceLog(data) {
      if (!data) return;
      
      // 每分钟只记录一次性能指标日志，避免日志过多
      const now = new Date();
      const lastPerfLog = this.logData.find(log => log.category === 'performance' && log.type === 'metrics');
      if (lastPerfLog) {
        const lastTime = new Date(lastPerfLog.timestamp);
        if (now - lastTime < 60000) { // 小于1分钟不记录
          return;
        }
      }
      
      this.logData.push({
        timestamp: new Date().toISOString(),
        level: 'info',
        category: 'performance',
        type: 'metrics',
        message: `性能指标: TPS ${data.tps?.toFixed(2) || 0}, 响应时间 ${data.responseTime?.toFixed(2) || 0}ms, 用户数 ${data.users || 0}, 错误率 ${data.errorRate?.toFixed(2) || 0}%`,
        details: JSON.stringify({
          tps: data.tps?.toFixed(2) || 0,
          responseTime: data.responseTime?.toFixed(2) || 0,
          users: data.users || 0,
          errorRate: data.errorRate?.toFixed(2) || 0
        }, null, 2)
      });
      
      // 保持最新2000条日志
      if (this.logData.length > 2000) {
        this.logData = this.logData.slice(-2000);
      }
      
      this.scrollToLogBottom();
    },
    
    // 添加事件日志
    addEventLog(title, message, level = 'info') {
      this.logData.push({
        timestamp: new Date().toISOString(),
        level,
        category: 'event',
        type: 'event',
        message: `${title}: ${message}`
      });
      
      // 保持最新2000条日志
      if (this.logData.length > 2000) {
        this.logData = this.logData.slice(-2000);
      }
      
      this.scrollToLogBottom();
    },
    
    // 添加请求日志
    addRequestLog(data) {
      if (!data || !data.data) return;
      
      const reqData = data.data;
      const isSuccess = data.type === 'request_success';
      const level = isSuccess ? 'info' : 'error';
      
      const message = isSuccess 
        ? `请求成功: ${reqData.method || 'GET'} ${reqData.url || '/'} (${reqData.response_time || 0}ms)`
        : `请求失败: ${reqData.method || 'GET'} ${reqData.url || '/'} - ${reqData.error || '未知错误'}`;
      
      this.logData.push({
        timestamp: new Date().toISOString(),
        level,
        category: 'request',
        type: isSuccess ? 'success' : 'failure',
        message,
        details: JSON.stringify({
          method: reqData.method || 'GET',
          url: reqData.url || '/',
          status: reqData.status || (isSuccess ? 200 : 500),
          response_time: reqData.response_time || 0,
          error: reqData.error || null,
          exception: reqData.exception || null
        }, null, 2),
        formatted: {
          method: reqData.method || 'GET',
          url: reqData.url || '/',
          status: reqData.status || (isSuccess ? 200 : 500),
          isFormatted: true
        }
      });
      
      // 保持最新2000条日志
      if (this.logData.length > 2000) {
        this.logData = this.logData.slice(-2000);
      }
      
      this.scrollToLogBottom();
    },
    
    // 获取日志样式
    getLogClass(level) {
      return `log-${level}`
    },
    
    // 获取请求状态样式
    getStatusClass(status) {
      if (!status) return '';
      const code = parseInt(status);
      if (code >= 200 && code < 300) return 'status-success';
      if (code >= 300 && code < 400) return 'status-redirect';
      if (code >= 400 && code < 500) return 'status-client-error';
      if (code >= 500) return 'status-server-error';
      return '';
    },
    
    // 获取HTTP方法样式
    getMethodClass(method) {
      if (!method) return '';
      switch(method.toUpperCase()) {
        case 'GET': return 'method-get';
        case 'POST': return 'method-post';
        case 'PUT': return 'method-put';
        case 'DELETE': return 'method-delete';
        case 'PATCH': return 'method-patch';
        case 'HEAD': return 'method-head';
        case 'OPTIONS': return 'method-options';
        default: return '';
      }
    },
    
    // 获取日志类别图标
    getLogCategoryIcon(category) {
      switch(category) {
        case 'system': return 'Monitor';
        case 'request': return 'Connection';
        case 'error': return 'CircleClose';
        case 'performance': return 'DataAnalysis';
        case 'event': return 'Bell';
        default: return 'Document';
      }
    },
    
    // 加载日志数据
    async loadLogData() {
      try {
        // 构建查询参数
        const params = {
          level: this.logLevel === 'all' ? '' : this.logLevel,
          limit: 2000, // 增加日志获取数量
          offset: 0
        }

        const response = await this.$api.getTaskReportLogs(this.reportId, params)
        // 增强日志数据
        this.logData = (response.data.logs || []).map(log => this.enhanceLogData(log));

        // 添加初始化完成事件日志
        if (this.logData.length === 0) {
          this.logData.push({
            timestamp: new Date().toISOString(),
            level: 'info',
            category: 'event',
            type: 'event',
            message: '日志初始化: 日志系统已初始化，等待测试数据...'
          });
        }
        
        // 滚动到日志底部
        this.scrollToLogBottom();
      } catch (error) {
        // 清空日志数据，不生成模拟日志
        this.logData = []
        // 添加错误日志
        this.logData.push({
          timestamp: new Date().toISOString(),
          level: 'error',
          category: 'event',
          type: 'event',
          message: `日志加载失败: ${error.message || '未知错误'}`
        });
        
        // 滚动到日志底部
        this.scrollToLogBottom();
      }
    },

    // 重新运行测试
    async rerunTest() {
      try {
        // 确认操作
        await this.$confirm(
          `将使用相同的测试配置，创建新的测试报告进行重新测试？`,
          '确认重新运行',
          {
            confirmButtonText: '确定运行',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }
        );

        // 显示重新运行开始的提示
        this.$message.info('正在启动测试，请稍候...');

        // 获取原始任务配置
        // task 字段可能是一个对象或者一个ID
        let taskId = null;


        if (this.reportData.task) {
          // 如果 task 是对象，取其 id
          if (typeof this.reportData.task === 'object' && this.reportData.task.id) {
            taskId = this.reportData.task.id;
          } else if (typeof this.reportData.task === 'number') {
            // 如果 task 直接是 ID
            taskId = this.reportData.task;
          }
        }

        // 如果还是没有找到，尝试其他字段
        if (!taskId) {
          taskId = this.reportData.taskId || this.reportData.task_id;
        }

        if (!taskId) {
          throw new Error('无法获取任务ID');
        }

        // 获取环境ID
        let envId = null;
        if (this.reportData.env) {
          // 如果env是对象，取其id
          envId = typeof this.reportData.env === 'object' ? this.reportData.env.id : this.reportData.env;
        } else {
          // 尝试其他字段
          envId = this.reportData.envId || this.reportData.env_id;
        }

        // 调用现有的运行任务API来实现重新运行
        const response = await this.$api.runTask(taskId, {
          rerun: true,
          copy_settings: true,
          env_id: envId, // 添加环境ID参数
          new_report_name: `${this.reportData.reportName}_重跑_${new Date().toISOString().slice(0, 16).replace('T', '_').replace(/:/g, '')}`
        });

        if (response.status === 200) {
          this.$message.success('测试重新运行成功！');

          // 获取新报告ID
          const newReportId = response.data.report_id || response.data.id;

          if (newReportId) {
            // 跳转到新的报告详情页面
            this.$router.push({
              name: 'PerformanceResult-Detail',
              params: { id: newReportId }
            });
          } else {
            // 如果没有返回新报告ID，刷新当前页面
            setTimeout(() => {
              location.reload();
            }, 2000);
          }
        }

      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消重新运行');
          return;
        }
        this.$message.error('重新运行失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      }
    },

    // 验证测试是否真正完成
    async verifyTestCompletion() {
      try {

        // 重新获取报告数据来验证状态
        const response = await this.$api.getTaskReportDetail(this.reportId);
        const latestReportData = response.data;


        // 检查多个条件来确认测试真正完成
        const isStatusCompleted = latestReportData.reportStatus === '0';
        const hasEndTime = latestReportData.endTime && latestReportData.endTime !== null;
        const hasFinalData = latestReportData.totalRequests && latestReportData.totalRequests > 0;


        // 只有当所有条件都满足时，才认为测试真正完成
        if (isStatusCompleted && (hasEndTime || hasFinalData)) {
          this.taskType = '已完成';
          this.reportData.reportStatus = '0';

          // 更新报告数据
          Object.assign(this.reportData, latestReportData);

          // 停止所有实时数据更新
          this.stopAllRealTimeUpdates();

          // 显示完成通知
          this.$message.success('性能测试已完成');

          // 重新生成图表数据
          this.generateChartData();

        } else {

          // 如果测试还没真正完成，继续等待并重新验证
          setTimeout(() => {
            this.verifyTestCompletion();
          }, 5000); // 5秒后重新验证
        }

      } catch (error) {

        // 如果验证失败，降级处理：直接更新为完成状态
        this.taskType = '已完成';
        this.reportData.reportStatus = '0';
        this.stopAllRealTimeUpdates();
        this.loadReportData();
      }
    },
    updateBasicMetricsFromWebSocket(totalStats) {
      // 更新所有实时指标
      if (totalStats.current_rps !== undefined) {
        this.reportData.avgTps = totalStats.current_rps;
      }
      if (totalStats.avg_response_time !== undefined) {
        this.reportData.avgResponseTime = totalStats.avg_response_time;
      }
      if (totalStats.min_response_time !== undefined) {
        this.reportData.minResponseTime = totalStats.min_response_time;
      }
      if (totalStats.max_response_time !== undefined) {
        this.reportData.maxResponseTime = totalStats.max_response_time;
      }
      if (totalStats.median_response_time !== undefined) {
        this.reportData.p50ResponseTime = totalStats.median_response_time;
      }
      if (totalStats.p90_response_time !== undefined) {
        this.reportData.p90ResponseTime = totalStats.p90_response_time;
      }
      if (totalStats.p95_response_time !== undefined) {
        this.reportData.p95ResponseTime = totalStats.p95_response_time;
      }
      if (totalStats.p99_response_time !== undefined) {
        this.reportData.p99ResponseTime = totalStats.p99_response_time;
      }
      if (totalStats.num_requests !== undefined) {
        this.reportData.totalRequests = totalStats.num_requests;
      }
      if (totalStats.num_failures !== undefined) {
        this.reportData.failedRequests = totalStats.num_failures;
        this.reportData.successRequests = (totalStats.num_requests || 0) - totalStats.num_failures;
      }
      if (totalStats.error_rate !== undefined) {
        this.reportData.errorRate = totalStats.error_rate;
      }
      if (totalStats.current_users !== undefined) {
        this.reportData.currentUsers = totalStats.current_users;
      }
      if (totalStats.elapsed_time !== undefined) {
        this.reportData.duration = Math.floor(totalStats.elapsed_time);
      }

      // 强制更新视图以确保数据同步显示
      this.$forceUpdate();
    },

    // 加载报告数据
    async loadReportData() {
      try {
        const response = await this.$api.getTaskReportDetail(this.reportId)
        this.reportData = response.data
        this.taskName = this.reportData.reportName
        this.desc = this.reportData.resultAnalyse || '暂无分析结果'
        this.taskType = this.getStatusText(this.reportData.reportStatus)

        // 如果报告已完成或失败，生成分析结果
        if (this.reportData.reportStatus === '0' || this.reportData.reportStatus === '99') {
          this.generateAnalysisResult()
        }

        // 生成图表数据
        this.generateChartData()

        // 如果测试正在运行，启动WebSocket连接和实时数据更新
        if (this.reportData.reportStatus === '1') {
          this.initWebSocket()
          // 启动实时数据更新（轮询）
          this.startRealTimeDataUpdate()
        }
      } catch (error) {
        this.$message.error('加载报告数据失败')
      }
    },

    // 生成分析结果
    generateAnalysisResult() {
      if (!this.reportData) return

      let analysisText = this.desc || ''

      // 如果没有分析结果，根据报告状态生成默认分析
      if (!analysisText || analysisText === '暂无分析结果') {
        if (this.reportData.reportStatus === '0') {
          // 测试成功完成的分析
          const successRate = this.getSuccessRate()
          const avgResponseTime = (this.reportData.avgResponseTime || 0).toFixed(2)
          const avgTps = this.reportData.avgTps || 0
          const errorRate = this.reportData.errorRate || 0

          analysisText = `测试已成功完成。\n`
          analysisText += `总体性能表现：平均响应时间 ${avgResponseTime}ms，平均TPS ${avgTps}，成功率 ${successRate}%。\n`

          if (avgResponseTime < 100) {
            analysisText += `响应时间表现优秀，系统响应迅速。`
          } else if (avgResponseTime < 500) {
            analysisText += `响应时间表现良好，符合一般性能要求。`
          } else if (avgResponseTime < 1000) {
            analysisText += `响应时间偏高，建议进行性能优化。`
          } else {
            analysisText += `响应时间过高，存在明显性能瓶颈，需要立即优化。`
          }

          if (errorRate > 5) {
            analysisText += `\n错误率较高(${errorRate}%)，建议检查系统稳定性。`
          } else if (errorRate > 1) {
            analysisText += `\n存在少量错误(${errorRate}%)，建议关注异常情况。`
          }

        } else if (this.reportData.reportStatus === '99') {
          // 测试失败的分析
          analysisText = `测试运行失败。\n`

          if (this.reportData.totalRequests > 0) {
            const failedRequests = this.reportData.failedRequests || 0
            const errorRate = this.reportData.errorRate || 0
            analysisText += `在执行 ${this.reportData.totalRequests} 个请求中，失败 ${failedRequests} 个，错误率 ${errorRate}%。\n`
          }

          analysisText += `建议检查：\n`
          analysisText += `1. 目标服务是否正常运行\n`
          analysisText += `2. 网络连接是否稳定\n`
          analysisText += `3. 测试脚本配置是否正确\n`
          analysisText += `4. 服务器资源是否充足`
        }
      }

      // 添加资源使用情况分析
      if (this.reportData.avgCpu && this.reportData.avgMemory) {
        analysisText += `\n\n资源使用情况：平均CPU ${this.reportData.avgCpu}%，平均内存 ${this.reportData.avgMemory}%。`

        if (this.reportData.avgCpu > 80) {
          analysisText += `CPU使用率过高，可能成为性能瓶颈。`
        } else if (this.reportData.avgMemory > 85) {
          analysisText += `内存使用率过高，建议增加内存或优化内存使用。`
        }
      }

      this.desc = analysisText
    },

    // 加载监控数据
    async loadMonitoringData() {
      try {
        const response = await this.$api.getSystemResourceStatus()
        const currentData = response.data.current || {}

        // 转换后端数据格式为前端期望的格式
        this.monitoringData = {
          cpu_percent: currentData.cpu?.percent || 0,
          memory_percent: currentData.memory?.percent || 0,
          disk_percent: currentData.disk?.percent || 0,
          network_sent: currentData.network?.bytes_sent || 0,
          network_recv: currentData.network?.bytes_recv || 0,
          active_connections: currentData.connections || 0,
          current_rps: currentData.rps || 0,
          current_users: currentData.users || 0,
          error_rate: currentData.error_rate || 0,
          server_type: currentData.server_type || 'single',
          cpu_cores: currentData.cpu?.count || 0,
          total_memory: currentData.memory?.total || 0,
          uptime: currentData.uptime || null
        }
      } catch (error) {
        console.error('加载监控数据失败:', error)
        // 清空监控数据，不显示模拟数据
        this.monitoringData = {
          cpu_percent: 0,
          memory_percent: 0,
          disk_percent: 0,
          network_sent: 0,
          network_recv: 0,
          active_connections: 0,
          current_rps: 0,
          current_users: 0,
          error_rate: 0,
          server_type: 'unknown',
          cpu_cores: 0,
          total_memory: 0,
          uptime: null
        }
      }
    },

    // 加载目标服务数据
    async loadTargetServiceData() {
      try {
        const response = await this.$api.getTargetServiceStatus(this.reportId)
        this.targetServiceData = response.data || {}
      } catch (error) {
        console.error('加载目标服务数据失败:', error)
        // 清空目标服务数据，不显示模拟数据
        this.targetServiceData = {
          service_status: 'unknown',
          connection_pool_active: 0,
          connection_pool_total: 0,
          db_connections: 0,
          cache_hit_rate: 0,
          response_time_trend: {
            labels: [],
            values: []
          },
          recent_errors: []
        }
      }
    },

    // 刷新日志数据
    async refreshLogData() {
      await this.loadLogData()
      this.$message.success('日志已刷新')
      this.scrollToLogBottom()
    },

    // 清空日志显示
    clearLogs() {
      this.logData = []
      this.$message.success('日志已清空')
    },



    // 初始化空的图表数据
    initEmptyChartData() {
      this.xData = [];
      this.responseTimeData = [];
      this.rpsData = [];
      this.tpsData = [];
      this.usersData = [];
      this.p50Data = [];
      this.p90Data = [];
      this.p95Data = [];
      this.p99Data = [];
      this.errorRateData = [];
    },

    // 生成图表数据
    generateChartData() {
      console.log('开始生成图表数据');

      // 初始化空的图表数据
      this.initEmptyChartData();

      let dataUpdated = false;

      if (this.reportData.reportResult) {
        try {
          const result = JSON.parse(this.reportData.reportResult);
          if (result.stats_history && result.stats_history.length > 0) {
            this.updateChartDataFromHistory(result.stats_history);
            dataUpdated = true;
          } else if (result.detailed_stats && this.reportData.reportStatus === '0') {
            this.updateChartDataFromDetailedStats(result);
            dataUpdated = true;
          }
        } catch (error) {
          console.error('解析报告结果失败:', error);
        }
      }

      // 如果没有历史数据且任务已完成，使用报告中的基础数据生成图表
      if (!dataUpdated && this.reportData.totalRequests && this.reportData.totalRequests > 0 && this.reportData.reportStatus === '0') {
        this.generateChartFromReportData();
        dataUpdated = true;
      }

      // 如果是运行中的任务，启动实时数据更新
      if (!dataUpdated && this.reportData.reportStatus === '1') {
        console.log('测试运行中，启动实时数据更新');
        this.startRealTimeDataUpdate();
      } else if (!dataUpdated) {
        console.log('无可用数据，显示空图表');
      }

      // 更新详细指标数据表格
      this.$nextTick(() => {
        if (this.activeIndex === '1') {
          // 如果当前在指标详情页，强制更新表格
          const tableElement = this.$refs.table;
          if (tableElement) {
            tableElement.$forceUpdate();
          }
          // 也强制更新组件本身
          this.$forceUpdate();
        }
      });
    },

    // 从历史数据更新图表
    updateChartDataFromHistory(statsHistory) {
      this.xData = [];
      this.responseTimeData = [];
      this.rpsData = [];
      this.tpsData = [];
      this.usersData = [];
      this.p50Data = [];
      this.p90Data = [];
      this.p95Data = [];
      this.p99Data = [];
      this.errorRateData = [];

      // 清空接口数据
      this.interfaceChartData = {
        responseTime: {},
        rps: {},
        tps: {},
        users: {},
        p50: {},
        p90: {},
        p95: {},
        p99: {},
        errorRate: {}
      };
      this.availableInterfaces = [];

      // 添加更新realTimeData的代码，使用最后一个数据点，以便详细指标能够显示
      if (statsHistory.length > 0) {
        const lastStats = statsHistory[statsHistory.length - 1];
        this.realTimeData = {
          total: lastStats.total || {},
          detailed_stats: lastStats.detailed_stats || {}
        };
      }

      statsHistory.forEach((stat, index) => {
        // 处理时间戳
        const timestamp = stat.timestamp || new Date().toISOString();
        this.xData.push(new Date(timestamp).toLocaleTimeString());

        // 从total统计数据中提取指标
        const total = stat.total || {};
        this.responseTimeData.push(total.avg_response_time || 0);
        this.rpsData.push(total.current_rps || 0);
        this.tpsData.push(total.current_tps || total.current_rps || 0);
        this.usersData.push(total.current_users || 0);
        this.p50Data.push(total.p50_response_time || 0);
        this.p90Data.push(total.p90_response_time || 0);
        this.p95Data.push(total.p95_response_time || 0);
        this.p99Data.push(total.p99_response_time || 0);
        this.errorRateData.push(total.error_rate || 0);

        // 处理各接口的详细数据
        if (stat.detailed_stats) {
          Object.keys(stat.detailed_stats).forEach(key => {
            const stats = stat.detailed_stats[key];
            const method = this.getCorrectHttpMethod(key, stats);
            const interfaceName = this.getCorrectInterfaceName(key, stats);
            const uniqueKey = method + '_' + interfaceName;
            // 初始化接口数据数组
            if (!this.interfaceChartData.responseTime[uniqueKey]) {
              this.interfaceChartData.responseTime[uniqueKey] = [];
              this.interfaceChartData.rps[uniqueKey] = [];
              this.interfaceChartData.tps[uniqueKey] = [];
              this.interfaceChartData.users[uniqueKey] = [];
              this.interfaceChartData.p50[uniqueKey] = [];
              this.interfaceChartData.p90[uniqueKey] = [];
              this.interfaceChartData.p95[uniqueKey] = [];
              this.interfaceChartData.p99[uniqueKey] = [];
              this.interfaceChartData.errorRate[uniqueKey] = [];
            }
            // 添加接口数据
            this.interfaceChartData.responseTime[uniqueKey].push(stats.avg_response_time || 0);
            this.interfaceChartData.rps[uniqueKey].push(stats.current_rps || 0);
            this.interfaceChartData.tps[uniqueKey].push(stats.current_tps || stats.current_rps || 0);
            this.interfaceChartData.users[uniqueKey].push(stats.current_users || 0);
            this.interfaceChartData.p50[uniqueKey].push(stats.p50_response_time || 0);
            this.interfaceChartData.p90[uniqueKey].push(stats.p90_response_time || 0);
            this.interfaceChartData.p95[uniqueKey].push(stats.p95_response_time || 0);
            this.interfaceChartData.p99[uniqueKey].push(stats.p99_response_time || 0);
            this.interfaceChartData.errorRate[uniqueKey].push(stats.error_rate || 0);
            // 更新可用接口列表
            if (!this.availableInterfaces.includes(uniqueKey)) {
              this.availableInterfaces.push(uniqueKey);
            }
          });
        }
      });
    },

    // 从详细统计数据更新图表
    updateChartDataFromDetailedStats(result) {

      // 更新realTimeData以便详细指标能够显示
      this.realTimeData = {
        total: result.total || {},
        detailed_stats: result.detailed_stats || {}
      };

      // 创建单个数据点，用于已完成的测试
      const total = result.total || {};
      const timestamp = result.timestamp || new Date().toISOString();

      this.xData = [new Date(timestamp).toLocaleTimeString()];
      this.responseTimeData = [total.avg_response_time || 0];
      this.rpsData = [total.current_rps || 0];
      this.tpsData = [total.current_tps || total.current_rps || 0];
      this.usersData = [total.current_users || 0];
      this.p50Data = [total.p50_response_time || 0];
      this.p90Data = [total.p90_response_time || 0];
      this.p95Data = [total.p95_response_time || 0];
      this.p99Data = [total.p99_response_time || 0];
      this.errorRateData = [total.error_rate || 0];

      },

    // 从报告基础数据生成图表
    generateChartFromReportData() {
      // 使用报告中的现有数据
      const duration = this.reportData.duration || 300; // 默认5分钟
      const dataPoints = Math.min(duration / 10, 30); // 每10秒一个点，最多30个点

      this.xData = [];
      this.responseTimeData = [];
      this.rpsData = [];
      this.tpsData = [];
      this.usersData = [];
      this.p50Data = [];
      this.p90Data = [];
      this.p95Data = [];
      this.p99Data = [];
      this.errorRateData = [];

      // 计算基础值
      const avgResponse = this.reportData.avgResponseTime || 0;
      const avgTps = this.reportData.avgTps || 0;
      const totalRequests = this.reportData.totalRequests || 0;
      const avgRps = duration > 0 ? totalRequests / duration : avgTps;
      const p50Response = this.reportData.p50ResponseTime || avgResponse * 1.5;
      const p90Response = this.reportData.p90ResponseTime || avgResponse * 2;
      const p95Response = this.reportData.p95ResponseTime || avgResponse * 2.5;
      const p99Response = this.reportData.p99ResponseTime || avgResponse * 3;
      const errorRate = this.reportData.errorRate || 0;

      // 生成时间序列数据
      const startTime = this.reportData.startTime ? new Date(this.reportData.startTime) : new Date();

      for (let i = 0; i < dataPoints; i++) {
        const time = new Date(startTime.getTime() + i * 10000); // 每10秒
        this.xData.push(time.toLocaleTimeString());

        // 添加轻微的随机变化，使数据更真实
        const variation = 0.1; // 10%变化范围
        this.responseTimeData.push(this.addVariation(avgResponse, variation));
        this.rpsData.push(this.addVariation(avgRps, variation));
        this.tpsData.push(this.addVariation(avgTps, variation));
        this.usersData.push(Math.max(1, Math.floor(this.addVariation(50, variation)))); // 估算用户数
        this.p50Data.push(this.addVariation(p50Response, variation));
        this.p90Data.push(this.addVariation(p90Response, variation));
        this.p95Data.push(this.addVariation(p95Response, variation));
        this.p99Data.push(this.addVariation(p99Response, variation));
        this.errorRateData.push(Math.max(0, this.addVariation(errorRate, variation)));
      }

      },

    // 添加数据变化
    addVariation(baseValue, variationPercent) {
      const variation = (Math.random() - 0.5) * 2 * variationPercent;
      const newValue = baseValue * (1 + variation);
      return Math.max(0, Number(newValue.toFixed(2)));
    },


    // 生成真实感的随机数据
    generateRealisticData(count, min, max, type) {
      const data = [];
      let baseValue = (min + max) / 2;
      let trend = (Math.random() - 0.5) * 0.1; // 随机趋势

      for (let i = 0; i < count; i++) {
        // 添加趋势变化
        baseValue += trend * (max - min) * 0.05;

        // 添加随机波动
        const variation = (Math.random() - 0.5) * (max - min) * 0.3;
        let value = baseValue + variation;

        // 确保值在合理范围内
        value = Math.max(min, Math.min(max, value));

        // 针对不同类型的数据进行特殊处理
        if (type === 'error_rate') {
          value = Math.max(0, Math.min(10, value)); // 错误率不超过10%
        } else if (type === 'users') {
          value = Math.floor(value); // 用户数为整数
        }

        data.push(Number(value.toFixed(2)));

        // 偶尔改变趋势
        if (Math.random() < 0.1) {
          trend = (Math.random() - 0.5) * 0.1;
        }
      }

      return data;
    },

    // 启动实时数据更新
    startRealTimeDataUpdate() {
      console.log('启动实时数据更新');

      if (this.realTimeUpdateInterval) {
        clearInterval(this.realTimeUpdateInterval);
      }

      // 每3秒获取真实的报告数据
      this.realTimeUpdateInterval = setInterval(() => {
        this.fetchRealTimeReportData();
      }, 3000);
    },

    // 获取实时报告数据
    async fetchRealTimeReportData() {
      try {
        const response = await this.$api.getTaskReportDetail(this.reportId);
        const reportData = response.data;

        if (reportData.gui_url !== null && reportData.gui_url !== '') {
          this.guiUrl = reportData.gui_url
          if (this.hasGuiUrlLoaded === false) {
            this.refreshGUI()
          }
          this.hasGuiUrlLoaded = true
        }

        // 更新报告基础数据
        this.updateReportMetrics(reportData);

        // 更新reportResult以便压测列表能更新
        if (reportData.reportResult) {
          this.reportData.reportResult = reportData.reportResult;
        }

        // 如果有新的统计数据，更新图表
        if (reportData.reportResult) {
          try {
            const result = JSON.parse(reportData.reportResult);
            if (result.stats_history && result.stats_history.length > 0) {
              this.updateChartDataFromHistory(result.stats_history);
            } else if (result.total) {
              // 如果只有当前统计数据，添加到图表中
              this.addRealTimeDataFromStats(result.total, result.detailed_stats);
            }

            // 强制触发压测列表更新
            if (result.detailed_stats) {
              // 使用nextTick确保在DOM更新后触发
              this.$nextTick(() => {
                // 强制更新组件以刷新压测列表
                this.$forceUpdate();
                // 如果在指标详情页面，确保表格可见
                if (this.activeIndex === '1') {
                  const tableElement = this.$refs.table;
                  if (tableElement) {
                    tableElement.$forceUpdate();
                  }
                }
              });
            }
          } catch (error) {
            console.error('解析实时统计数据失败:', error);
          }
        }

        // 检查测试是否已完成
        if (reportData.reportStatus !== '1') {
          console.log('测试已完成，停止实时更新');
          this.stopAllRealTimeUpdates();
          // 重新加载完整数据
          await this.loadReportData();
        }

      } catch (error) {
        console.error('获取实时报告数据失败:', error);
        // 如果API调用失败，可能测试已经结束，停止更新
        this.stopAllRealTimeUpdates();
      }
    },

    // 停止所有实时数据更新
    stopAllRealTimeUpdates() {
      console.log('停止所有实时数据更新...');
      
      // 停止实时数据更新
      this.stopRealTimeDataUpdate();
      
      // 停止监控数据刷新
      this.stopMonitoringRefresh();
      
      // 停止目标服务数据刷新
      this.stopTargetServiceRefresh();
      
      // 停止自动刷新（包括日志）
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
        this.refreshInterval = null;
      }
      
      // 停止心跳检测
      if (this.heartbeatInterval) {
        clearInterval(this.heartbeatInterval);
        this.heartbeatInterval = null;
      }
      
      // 关闭自动刷新开关
      this.autoRefresh = false;

      // 清理WebSocket连接
      this.cleanupWebSocket();
      
      console.log('所有实时数据更新已停止');
    },

    // 停止实时数据更新
    stopRealTimeDataUpdate() {
      if (this.realTimeUpdateInterval) {
        clearInterval(this.realTimeUpdateInterval);
        this.realTimeUpdateInterval = null;
        console.log('实时数据更新已停止');
      }
    },

    // 更新报告指标数据
    updateReportMetrics(reportData) {
      // 更新基础指标
      if (reportData.avgTps !== undefined) this.reportData.avgTps = reportData.avgTps;
      if (reportData.avgResponseTime !== undefined) this.reportData.avgResponseTime = reportData.avgResponseTime;
      if (reportData.avgCpu !== undefined) this.reportData.avgCpu = reportData.avgCpu;
      if (reportData.avgMemory !== undefined) this.reportData.avgMemory = reportData.avgMemory;
      if (reportData.totalRequests !== undefined) this.reportData.totalRequests = reportData.totalRequests;
      if (reportData.successRequests !== undefined) this.reportData.successRequests = reportData.successRequests;
      if (reportData.failedRequests !== undefined) this.reportData.failedRequests = reportData.failedRequests;
      if (reportData.errorRate !== undefined) this.reportData.errorRate = reportData.errorRate;
      if (reportData.duration !== undefined) this.reportData.duration = reportData.duration;

      // 更新状态
      if (reportData.reportStatus !== undefined) {
        this.reportData.reportStatus = reportData.reportStatus;
        this.taskType = this.getStatusText(reportData.reportStatus);
      }
    },

    // 从统计数据添加实时数据点
    addRealTimeDataFromStats(totalStats, detailedStats = null) {
      const now = new Date().toLocaleTimeString();

      // 添加新的时间点
      this.xData.push(now);

      // 从真实统计数据中提取总体指标
      this.responseTimeData.push(totalStats.avg_response_time || 0);
      this.rpsData.push(totalStats.current_rps || 0);
      this.tpsData.push(totalStats.current_tps || totalStats.current_rps || 0);
      this.usersData.push(totalStats.current_users || 0);
      this.p50Data.push(totalStats.p50_response_time || 0);
      this.p90Data.push(totalStats.p90_response_time || 0);
      this.p95Data.push(totalStats.p95_response_time || 0);
      this.p99Data.push(totalStats.p99_response_time || 0);
      this.errorRateData.push(totalStats.error_rate || 0);

      // 处理各接口的详细数据
      if (detailedStats) {
        Object.entries(detailedStats).forEach(([key, stats]) => {
          const interfaceName = this.getCorrectInterfaceName(key, stats);  // 使用新的接口名称提取方法

          // 初始化接口数据数组
          if (!this.interfaceChartData.responseTime[interfaceName]) {
            this.interfaceChartData.responseTime[interfaceName] = [];
            this.interfaceChartData.rps[interfaceName] = [];
            this.interfaceChartData.tps[interfaceName] = [];
            this.interfaceChartData.users[interfaceName] = [];
            this.interfaceChartData.p50[interfaceName] = [];
            this.interfaceChartData.p90[interfaceName] = [];
            this.interfaceChartData.p95[interfaceName] = [];
            this.interfaceChartData.p99[interfaceName] = [];
            this.interfaceChartData.errorRate[interfaceName] = [];
          }

          // 添加接口数据
          this.interfaceChartData.responseTime[interfaceName].push(stats.avg_response_time || 0);
          this.interfaceChartData.rps[interfaceName].push(stats.current_rps || 0);
          this.interfaceChartData.tps[interfaceName].push(stats.current_tps || stats.current_rps || 0);
          this.interfaceChartData.users[interfaceName].push(stats.current_users || totalStats.current_users || 0);
          this.interfaceChartData.p50[interfaceName].push(stats.p50_response_time || 0);
          this.interfaceChartData.p90[interfaceName].push(stats.p90_response_time || 0);
          this.interfaceChartData.p95[interfaceName].push(stats.p95_response_time || 0);
          this.interfaceChartData.p99[interfaceName].push(stats.p99_response_time || 0);
          this.interfaceChartData.errorRate[interfaceName].push(stats.error_rate || 0);

          // 更新可用接口列表
          if (!this.availableInterfaces.includes(interfaceName)) {
            this.availableInterfaces.push(interfaceName);
          }
        });
      }

    },

    // 生成下一个数值（基于上一个值的小幅波动）
    generateNextValue(dataArray, min, max) {
      if (dataArray.length === 0) {
        return (min + max) / 2;
      }

      const lastValue = dataArray[dataArray.length - 1];
      const range = max - min;
      const maxChange = range * 0.1; // 最大变化10%

      const change = (Math.random() - 0.5) * maxChange;
      let newValue = lastValue + change;

      // 确保值在合理范围内
      newValue = Math.max(min, Math.min(max, newValue));

      return Number(newValue.toFixed(2));
    },



    // 更新图表数据
    updateChartData() {
      if (this.realTimeData) {
        const now = new Date().toLocaleTimeString();
        this.xData.push(now);

        // 保持最新20个数据点
        if (this.xData.length > 20) {
          this.xData.shift();
          this.responseTimeData.shift();
          this.rpsData.shift();
          this.tpsData.shift();
          this.usersData.shift();
          this.p50Data.shift();
          this.p90Data.shift();
          this.p95Data.shift();
          this.p99Data.shift();
          this.errorRateData.shift();

          // 同时清理接口数据
          Object.keys(this.interfaceChartData.responseTime).forEach(interfaceName => {
            this.interfaceChartData.responseTime[interfaceName].shift();
            this.interfaceChartData.rps[interfaceName].shift();
            this.interfaceChartData.tps[interfaceName].shift();
            this.interfaceChartData.users[interfaceName].shift();
            this.interfaceChartData.p50[interfaceName].shift();
            this.interfaceChartData.p90[interfaceName].shift();
            this.interfaceChartData.p95[interfaceName].shift();
            this.interfaceChartData.p99[interfaceName].shift();
            this.interfaceChartData.errorRate[interfaceName].shift();
          });
        }

        // 从实时数据中提取总体指标
        const total = this.realTimeData.total || {};
        this.responseTimeData.push(total.avg_response_time || 0);
        this.rpsData.push(total.current_rps || 0);
        this.tpsData.push(total.current_tps || total.current_rps || 0);
        this.usersData.push(total.current_users || 0);
        this.p50Data.push(total.p50_response_time || 0);
        this.p90Data.push(total.p90_response_time || 0);
        this.p95Data.push(total.p95_response_time || 0);
        this.p99Data.push(total.p99_response_time || 0);
        this.errorRateData.push(total.error_rate || 0);

        // 从实时数据中提取每个接口的指标
        if (this.realTimeData.detailed_stats) {
          Object.entries(this.realTimeData.detailed_stats).forEach(([key, stats]) => {
            const interfaceName = this.getCorrectInterfaceName(key, stats);  // 使用新的接口名称提取方法

            // 初始化接口数据数组
            if (!this.interfaceChartData.responseTime[interfaceName]) {
              this.interfaceChartData.responseTime[interfaceName] = [];
              this.interfaceChartData.rps[interfaceName] = [];
              this.interfaceChartData.tps[interfaceName] = [];
              this.interfaceChartData.users[interfaceName] = [];
              this.interfaceChartData.p50[interfaceName] = [];
              this.interfaceChartData.p90[interfaceName] = [];
              this.interfaceChartData.p95[interfaceName] = [];
              this.interfaceChartData.p99[interfaceName] = [];
              this.interfaceChartData.errorRate[interfaceName] = [];
            }

            // 添加接口数据
            this.interfaceChartData.responseTime[interfaceName].push(stats.avg_response_time || 0);
            this.interfaceChartData.rps[interfaceName].push(stats.current_rps || 0);
            this.interfaceChartData.tps[interfaceName].push(stats.current_tps || stats.current_rps || 0);
            this.interfaceChartData.users[interfaceName].push(stats.current_users || total.current_users || 0);
            this.interfaceChartData.p50[interfaceName].push(stats.p50_response_time || 0);
            this.interfaceChartData.p90[interfaceName].push(stats.p90_response_time || 0);
            this.interfaceChartData.p95[interfaceName].push(stats.p95_response_time || 0);
            this.interfaceChartData.p99[interfaceName].push(stats.p99_response_time || 0);
            this.interfaceChartData.errorRate[interfaceName].push(stats.error_rate || 0);

            // 更新可用接口列表
            if (!this.availableInterfaces.includes(interfaceName)) {
              this.availableInterfaces.push(interfaceName);
            }
          });
        }

      }
    },

    // 获取详细指标数据
    getDetailedMetrics() {
      if (!this.reportData) return []

      // 如果有实时数据，优先使用实时数据
      if (this.realTimeData) {
        if (this.realTimeData.detailed_stats || this.realTimeData.total) {
          // 如果没有detailed_stats，创建一个空对象
          const detailedStats = this.realTimeData.detailed_stats || {};
          return this.formatDetailedStats(detailedStats);
        }
      }

      // 如果有reportResult中的详细统计数据，使用历史数据
      if (this.reportData.reportResult) {
        try {
          const result = JSON.parse(this.reportData.reportResult);

          // 将total数据保存到realTimeData以便格式化时使用
          if (result.total) {
            this.realTimeData = this.realTimeData || {};
            this.realTimeData.total = result.total;
          }

          if (result.detailed_stats) {
            return this.formatDetailedStats(result.detailed_stats);
          }
        } catch (error) {
          console.error('解析详细统计数据失败:', error);
        }
      }

      // 只有在任务已完成且有实际数据时，才显示总体数据
      if (this.reportData.reportStatus === '0' && this.reportData.totalRequests && this.reportData.totalRequests > 0) {
        return [{
          name: this.reportData.reportName || '总体',
          method: 'ALL',
          totalRequests: this.reportData.totalRequests || 0,
          successRequests: this.reportData.successRequests || 0,
          failedRequests: this.reportData.failedRequests || 0,
          maxResponseTime: this.reportData.maxResponseTime || 0,
          minResponseTime: this.reportData.minResponseTime || 0,
          avgResponseTime: this.reportData.avgResponseTime || 0,
          p50ResponseTime: this.reportData.p50ResponseTime || 0, // 添加p50ResponseTime
          p90ResponseTime: this.reportData.p90ResponseTime || 0,
          p95ResponseTime: this.reportData.p95ResponseTime || 0, // 添加p95ResponseTime
          p99ResponseTime: this.reportData.p99ResponseTime || 0,
          rps: this.calculateRPS(),
          avgRps: this.calculateAvgRPS(),
          avgTps: this.reportData.avgTps || 0,
          avgTpsAvg: this.reportData.avgTps || 0,
          errorRate: (this.reportData.errorRate || 0).toFixed(2)
        }]
      }

      // 如果是运行中的任务或没有数据，返回空数组
      return []
    },

    // 格式化详细统计数据
    formatDetailedStats(detailedStats) {
      const results = [];

      // 收集所有接口数据用于计算总体统计
      const interfaceData = [];
      for (const [key, stats] of Object.entries(detailedStats)) {
        const interfaceMetrics = {
          name: this.getCorrectInterfaceName(key, stats),
          method: this.getCorrectHttpMethod(key, stats),
          totalRequests: stats.num_requests || 0,
          successRequests: stats.success_requests || (stats.num_requests - stats.num_failures) || 0,
          failedRequests: stats.num_failures || 0,
          maxResponseTime: Math.round(stats.max_response_time || 0),
          minResponseTime: Math.round(stats.min_response_time || 0),
          avgResponseTime: Math.round(stats.avg_response_time || 0),
          p50ResponseTime: Math.round(stats.median_response_time || 0), // 添加p50ResponseTime
          p90ResponseTime: Math.round(stats.p90_response_time || 0),
          p95ResponseTime: Math.round(stats.p95_response_time || 0), // 添加p95ResponseTime
          p99ResponseTime: Math.round(stats.p99_response_time || 0),
          rps: typeof stats.current_rps === 'number' ? Number(stats.current_rps).toFixed(2) : '0.00',
          avgRps: typeof stats.current_rps === 'number' ? Number(stats.current_rps).toFixed(2) : '0.00',
          avgTps: typeof stats.current_rps === 'number' ? Number(stats.current_rps).toFixed(2) : '0.00',
          avgTpsAvg: typeof stats.current_rps === 'number' ? Number(stats.current_rps).toFixed(2) : '0.00',
          errorRate: typeof stats.error_rate === 'number' ? Number(stats.error_rate).toFixed(2) : '0.00',
          currentUsers: stats.current_users || stats.users || 0
        };
        interfaceData.push(interfaceMetrics);
        results.push(interfaceMetrics);
      }

      // 计算总体统计数据（所有接口相加）
      if (interfaceData.length > 0) {
        const totalMetrics = this.calculateTotalFromInterfaces(interfaceData);
        results.unshift(totalMetrics); // 将总体数据放在第一位
      } else if (this.realTimeData && this.realTimeData.total) {
        // 如果没有接口数据，使用实时数据中的总体数据
        const total = this.realTimeData.total;
        const duration = this.reportData.duration || 1;
        const avgRps = total.num_requests ? (total.num_requests / duration).toFixed(2) : '0.00';

        results.unshift({
          name: '总体',
          method: 'ALL',
          totalRequests: total.num_requests || 0,
          successRequests: (total.num_requests - total.num_failures) || 0,
          failedRequests: total.num_failures || 0,
          maxResponseTime: Math.round(total.max_response_time || 0),
          minResponseTime: Math.round(total.min_response_time || 0),
          avgResponseTime: Math.round(total.avg_response_time || 0),
          p50ResponseTime: Math.round(total.median_response_time || 0), // 添加p50ResponseTime
          p90ResponseTime: Math.round(total.p90_response_time || 0),
          p95ResponseTime: Math.round(total.p95_response_time || 0), // 添加p95ResponseTime
          p99ResponseTime: Math.round(total.p99_response_time || 0),
          rps: (total.current_rps || 0).toFixed(2),
          avgRps: avgRps,
          avgTps: (total.current_tps || total.current_rps || 0).toFixed(2),
          avgTpsAvg: avgRps,
          errorRate: (total.error_rate || 0).toFixed(2),
          currentUsers: total.current_users || this.getCurrentUserCount()
        });
      } else if (this.reportData && this.reportData.totalRequests > 0) {
        // 如果没有实时数据，使用报告的总体数据
        const duration = this.reportData.duration || 1;
        const avgRps = this.reportData.totalRequests ? (this.reportData.totalRequests / duration).toFixed(2) : '0.00';

        results.unshift({
          name: '总体',
          method: 'ALL',
          totalRequests: this.reportData.totalRequests || 0,
          successRequests: this.reportData.successRequests || 0,
          failedRequests: this.reportData.failedRequests || 0,
          maxResponseTime: Math.round(this.reportData.maxResponseTime || 0),
          minResponseTime: Math.round(this.reportData.minResponseTime || 0),
          avgResponseTime: Math.round(this.reportData.avgResponseTime || 0),
          p50ResponseTime: Math.round(this.reportData.p50ResponseTime || 0), // 添加p50ResponseTime
          p90ResponseTime: Math.round(this.reportData.p90ResponseTime || 0),
          p95ResponseTime: Math.round(this.reportData.p95ResponseTime || 0), // 添加p95ResponseTime
          p99ResponseTime: Math.round(this.reportData.p99ResponseTime || 0),
          rps: avgRps,
          avgRps: avgRps,
          avgTps: (this.reportData.avgTps || 0).toFixed(2),
          avgTpsAvg: (this.reportData.avgTps || 0).toFixed(2),
          errorRate: (this.reportData.errorRate || 0).toFixed(2),
          currentUsers: this.getCurrentUserCount()
        });
      }

      return results;
    },

    // 计算所有接口的总体统计（相加模式）
    calculateTotalFromInterfaces(interfaceData) {
      let totalRequests = 0;
      let totalSuccessRequests = 0;
      let totalFailedRequests = 0;
      let totalRps = 0;
      let totalTps = 0;
      let totalUsers = 0;
      let maxResponseTime = 0;
      let minResponseTime = Infinity;
      let weightedAvgResponseTime = 0;
      let weightedP50ResponseTime = 0; // 添加p50加权计算
      let weightedP90ResponseTime = 0;
      let weightedP95ResponseTime = 0; // 添加p95加权计算
      let weightedP99ResponseTime = 0;

      // 汇总所有接口的数据
      interfaceData.forEach(item => {
        totalRequests += item.totalRequests;
        totalSuccessRequests += item.successRequests;
        totalFailedRequests += item.failedRequests;
        totalRps += parseFloat(item.rps);
        totalTps += parseFloat(item.avgTps);
        totalUsers = Math.max(totalUsers, item.currentUsers || 0);
        maxResponseTime = Math.max(maxResponseTime, item.maxResponseTime);
        if (item.minResponseTime > 0) {
          minResponseTime = Math.min(minResponseTime, item.minResponseTime);
        }

        // 加权平均响应时间（按请求数加权）
        weightedAvgResponseTime += item.avgResponseTime * item.totalRequests;
        weightedP50ResponseTime += item.p50ResponseTime * item.totalRequests; // 添加p50加权计算
        weightedP90ResponseTime += item.p90ResponseTime * item.totalRequests;
        weightedP95ResponseTime += item.p95ResponseTime * item.totalRequests; // 添加p95加权计算
        weightedP99ResponseTime += item.p99ResponseTime * item.totalRequests;
      });

      // 计算加权平均
      const avgResponseTime = totalRequests > 0 ? Math.round(weightedAvgResponseTime / totalRequests) : 0;
      const p50ResponseTime = totalRequests > 0 ? Math.round(weightedP50ResponseTime / totalRequests) : 0; // 计算p50加权平均
      const p90ResponseTime = totalRequests > 0 ? Math.round(weightedP90ResponseTime / totalRequests) : 0;
      const p95ResponseTime = totalRequests > 0 ? Math.round(weightedP95ResponseTime / totalRequests) : 0; // 计算p95加权平均
      const p99ResponseTime = totalRequests > 0 ? Math.round(weightedP99ResponseTime / totalRequests) : 0;
      const errorRate = totalRequests > 0 ? ((totalFailedRequests / totalRequests) * 100).toFixed(2) : '0.00';

      if (minResponseTime === Infinity) {
        minResponseTime = 0;
      }

      return {
        name: '总体',
        method: 'ALL',
        totalRequests: totalRequests,
        successRequests: totalSuccessRequests,
        failedRequests: totalFailedRequests,
        maxResponseTime: maxResponseTime,
        minResponseTime: Math.round(minResponseTime),
        avgResponseTime: avgResponseTime,
        p50ResponseTime: p50ResponseTime, // 添加p50ResponseTime
        p90ResponseTime: p90ResponseTime,
        p95ResponseTime: p95ResponseTime, // 添加p95ResponseTime
        p99ResponseTime: p99ResponseTime,
        rps: totalRps.toFixed(2),
        avgRps: totalRps.toFixed(2),
        avgTps: totalTps.toFixed(2),
        avgTpsAvg: totalTps.toFixed(2),
        errorRate: errorRate,
        currentUsers: totalUsers || this.getCurrentUserCount()  // 如果没有接口级用户数，使用全局用户数
      };
    },

    // 计算总体统计
    calculateTotalStats(detailedResults) {
      const total = {
        name: '总体',
        method: 'ALL',
        totalRequests: 0,
        successRequests: 0,
        failedRequests: 0,
        maxResponseTime: 0,
        minResponseTime: Infinity,
        avgResponseTime: 0,
        p50ResponseTime: 0, // 添加p50ResponseTime
        p90ResponseTime: 0,
        p95ResponseTime: 0, // 添加p95ResponseTime
        p99ResponseTime: 0,
        rps: 0,
        avgRps: 0,
        avgTps: 0,
        avgTpsAvg: 0,
        errorRate: 0
      };

      let totalResponseTime = 0;
      let totalP50 = 0; // 添加p50累计
      let totalP90 = 0;
      let totalP95 = 0; // 添加p95累计
      let totalP99 = 0;

      detailedResults.forEach(item => {
        total.totalRequests += item.totalRequests;
        total.successRequests += item.successRequests;
        total.failedRequests += item.failedRequests;
        total.maxResponseTime = Math.max(total.maxResponseTime, item.maxResponseTime);
        total.minResponseTime = Math.min(total.minResponseTime, item.minResponseTime);
        total.rps += parseFloat(item.rps);
        total.avgRps += parseFloat(item.avgRps);
        total.avgTps += parseFloat(item.avgTps);
        total.avgTpsAvg += parseFloat(item.avgTpsAvg);

        // 加权平均响应时间
        totalResponseTime += item.avgResponseTime * item.totalRequests;
        totalP50 += item.p50ResponseTime * item.totalRequests; // 添加p50加权计算
        totalP90 += item.p90ResponseTime * item.totalRequests;
        totalP95 += item.p95ResponseTime * item.totalRequests; // 添加p95加权计算
        totalP99 += item.p99ResponseTime * item.totalRequests;
      });

      if (total.totalRequests > 0) {
        total.avgResponseTime = Math.round(totalResponseTime / total.totalRequests);
        total.p50ResponseTime = Math.round(totalP50 / total.totalRequests); // 计算p50加权平均
        total.p90ResponseTime = Math.round(totalP90 / total.totalRequests);
        total.p95ResponseTime = Math.round(totalP95 / total.totalRequests); // 计算p95加权平均
        total.p99ResponseTime = Math.round(totalP99 / total.totalRequests);
        total.errorRate = Number((total.failedRequests / total.totalRequests) * 100).toFixed(2);
      } else {
        total.errorRate = '0.00';
      }

      if (total.minResponseTime === Infinity) {
        total.minResponseTime = 0;
      }

      total.rps = Number(total.rps || 0).toFixed(2);
      total.avgRps = Number(total.avgRps || 0).toFixed(2);
      total.avgTps = Number(total.avgTps || 0).toFixed(2);
      total.avgTpsAvg = Number(total.avgTpsAvg || 0).toFixed(2);

      return total;
    },


    // 计算RPS
    calculateRPS() {
      if (!this.reportData) return '0.00'
      // 如果有实时数据，使用实时RPS
      if (this.realTimeData && this.realTimeData.total && typeof this.realTimeData.total.current_rps === 'number') {
        return Number(this.realTimeData.total.current_rps).toFixed(2)
      }
      // 否则根据总请求数和时长计算
      const duration = this.reportData.duration || 1
      const totalRequests = this.reportData.totalRequests || 0
      return Number(totalRequests / duration).toFixed(2)
    },

    // 计算平均RPS
    calculateAvgRPS() {
      if (!this.reportData) return '0.00'
      const duration = this.reportData.duration || 1
      const totalRequests = this.reportData.totalRequests || 0
      return Number(totalRequests / duration).toFixed(2)
    },

    // 生成报告摘要
    generateReportSummary() {
      if (!this.reportData) return '暂无数据'

      const avgRT = this.reportData.avgResponseTime || 0
      const p50RT = this.reportData.p50ResponseTime || 0
      const p90RT = this.reportData.p90ResponseTime || 0
      const p95RT = this.reportData.p95ResponseTime || 0
      const p99RT = this.reportData.p99ResponseTime || 0
      const rps = this.calculateRPS()
      const tps = this.reportData.avgTps || 0

      return `平均响应时间为${avgRT}ms；50%响应时间线的值为${p50RT}ms；90%响应时间线的值为${p90RT}ms；95%响应时间线的值为${p95RT}ms；99%响应时间线的值为${p99RT}ms；RPS为${rps}；TPS为${tps}`
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '--'
      return new Date(time).toLocaleString()
    },

    // 格式化响应时间
    formatResponseTime(time) {
      if (!time || typeof time !== 'number') return '0ms'
      return time < 1000 ? `${Number(time).toFixed(2)}ms` : `${Number(time/1000).toFixed(2)}s`
    },

    // 格式化持续时间
    formatDuration(seconds) {
      if (!seconds) return '0s'
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = seconds % 60
      return `${hours}h ${minutes}m ${secs}s`
    },

    // 格式化字节
    formatBytes(bytes) {
      if (!bytes || typeof bytes !== 'number' || isNaN(bytes)) return '0B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(Math.max(1, bytes)) / Math.log(k))
      const value = bytes / Math.pow(k, i)
      return parseFloat(Number(value).toFixed(2)) + sizes[Math.min(i, sizes.length - 1)]
    },

    // 获取任务类型文本
    getTaskTypeText(type) {
      const types = { '10': '普通任务', '20': '定时任务' }
      return types[type] || '未知'
    },

    // 获取运行模式文本
    getRunPatternText(pattern) {
      const patterns = { '10': '并发模式', '20': '阶梯模式' }
      return patterns[pattern] || '未知'
    },

    // 获取分布式模式文本
    getDistributedModeText(mode) {
      const modes = { 'single': '单独模式', 'distributed': '集合模式' }
      return modes[mode] || '未知'
    },

    // 获取状态文本
    getStatusText(status) {
      const statuses = { '1': '运行中', '0': '已完成', '99': '运行失败' }
      return statuses[status] || '未知'
    },

    // 获取CPU级别样式
    getCpuLevelClass(percent) {
      if (percent > 80) return 'metric-danger'
      if (percent > 60) return 'metric-warning'
      return 'metric-normal'
    },

    // 获取内存级别样式
    getMemoryLevelClass(percent) {
      if (percent > 85) return 'metric-danger'
      if (percent > 70) return 'metric-warning'
      return 'metric-normal'
    },

    // 获取错误率样式
    getErrorRateClass(rate) {
      if (rate > 5) return 'metric-danger'
      if (rate > 1) return 'metric-warning'
      return 'metric-normal'
    },



    // 获取日志样式
    getLogClass(level) {
      return `log-${level}`
    },

    // 刷新监控数据
    async refreshMonitoringData() {
      await this.loadMonitoringData()
      this.$message.success('监控数据已刷新')
    },


    // 切换自动刷新
    toggleAutoRefresh() {
      if (this.autoRefresh) {
        // 只有在测试运行时才启动轮询
        if (this.reportData.reportStatus === '1') {
          this.refreshInterval = setInterval(() => {
            this.loadMonitoringData()
            this.loadTargetServiceData()
            this.loadLogData()
          }, 10000) // 每10秒刷新

          // 如果测试正在运行，尝试重新连接WebSocket
          this.initWebSocket()
        } else {
          // 如果测试已完成，提示用户并关闭自动刷新
          this.$message.info('测试已完成，无需开启自动刷新')
          this.autoRefresh = false
          return
        }
      } else {
        if (this.refreshInterval) {
          clearInterval(this.refreshInterval)
          this.refreshInterval = null
        }
        // 关闭WebSocket连接
        this.cleanupWebSocket()
      }
    },

    // 获取WebSocket状态文本
    getWebSocketStatusText() {
      switch (this.wsConnectionStatus) {
        case 'connected':
          return '实时监控'
        case 'connecting':
          return '连接中'
        case 'disconnected':
          return '已断开'
        case 'error':
          return '连接错误'
        default:
          return '未连接'
      }
    },

    // 获取WebSocket状态类型
    getWebSocketStatusType() {
      switch (this.wsConnectionStatus) {
        case 'connected':
          return 'success'
        case 'connecting':
          return 'warning'
        case 'disconnected':
          return 'info'
        case 'error':
          return 'danger'
        default:
          return 'info'
      }
    },

    // 处理WebSocket状态点击
    handleWebSocketStatusClick() {
      switch (this.wsConnectionStatus) {
        case 'connected':
          this.$message.success('WebSocket连接正常')
          break
        case 'connecting':
          this.$message.info('正在连接WebSocket...')
          break
        case 'disconnected':
        case 'error':
          this.$confirm('WebSocket连接已断开，是否尝试重新连接？', '连接提示', {
            confirmButtonText: '重新连接',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.reconnectWebSocket()
          }).catch(() => {
            this.$message.info('已取消重连')
          })
          break
        default:
          if (this.reportData.reportStatus === '1') {
            this.initWebSocket()
          } else {
            this.$message.info('测试未运行，无需实时监控')
          }
      }
    },

    startEditing() {
      this.inputDlg = true;
      this.editingField = 'desc';
      this.$nextTick(() => {
        if (this.$refs.input) {
          this.$refs.input.focus();
        }
      });
    },
    editTaskName() {
      this.inputDlg = true;
      this.editingField = 'taskName';
      this.tempTaskName = this.taskName; // 保存原值以便取消时恢复
      this.$nextTick(() => {
        if (this.$refs.input) {
          this.$refs.input.focus();
        }
      });
    },
    cancelEditing() {
      this.inputDlg = false;
      // 如果是编辑任务名称且未保存，恢复原值
      if (this.editingField === 'taskName' && this.tempTaskName) {
        this.taskName = this.tempTaskName;
      }
    },

    // 保存任务名称
    async saveTaskName() {
      this.inputDlg = false;

      // 如果名称没有变化，不需要保存
      if (this.taskName === this.reportData.reportName) {
        return;
      }
      this.saveReport()
    },

    // 保存分析结果
    async saveAnalysis() {
      this.inputDlg = false;

      // 如果内容没有变化，不需要保存
      if (this.desc === this.reportData.resultAnalyse) {
        return;
      }
      this.saveReport()

    },
    handleSelect(index) {
      this.activeIndex = index;

      // 根据选择的标签页加载对应数据
      if (index === '1') {
        // 指标详情页 - 总是重新加载指标数据，以确保数据完整性
        if (this.reportData && this.reportData.reportResult) {
          // 重新生成图表数据和指标列表
          this.generateChartData();
          
          // 强制更新表格组件以确保数据显示
          this.$nextTick(() => {
            const tableElement = this.$refs.table;
            if (tableElement) {
              tableElement.$forceUpdate();
            }
            // 也强制更新组件本身
            this.$forceUpdate();
          });
        }
      } else if (index === '3' && !this.monitoringDataLoaded) {
        this.loadMonitoringData()
        this.monitoringDataLoaded = true

        // 如果测试正在运行，启动定时刷新监控数据
        if (this.reportData.reportStatus === '1' && this.autoRefresh) {
          this.startMonitoringRefresh()
        }
      } else if (index === '4' && !this.targetServiceDataLoaded) {
        this.loadTargetServiceData()
        this.targetServiceDataLoaded = true

        // 如果测试正在运行，启动定时刷新目标服务数据
        if (this.reportData.reportStatus === '1' && this.autoRefresh) {
          this.startTargetServiceRefresh()
        }
      } else if (index === '5') {
        if (!this.logDataLoaded) {
          this.loadLogData()
          this.logDataLoaded = true
        } else {
          // 如果日志数据已加载，只需滚动到底部
          this.scrollToLogBottom();
        }
      }

      // 离开监控页面时停止刷新
      if (index !== '3') {
        this.stopMonitoringRefresh()
      }
      if (index !== '4') {
        this.stopTargetServiceRefresh()
      }
    },

    // 启动监控数据刷新
    startMonitoringRefresh() {
      if (this.monitoringRefreshInterval) {
        clearInterval(this.monitoringRefreshInterval)
      }
      this.monitoringRefreshInterval = setInterval(() => {
        this.loadMonitoringData()
      }, 5000) // 每5秒刷新一次
    },

    // 停止监控数据刷新
    stopMonitoringRefresh() {
      if (this.monitoringRefreshInterval) {
        clearInterval(this.monitoringRefreshInterval)
        this.monitoringRefreshInterval = null
      }
    },

    // 启动目标服务数据刷新
    startTargetServiceRefresh() {
      if (this.targetServiceRefreshInterval) {
        clearInterval(this.targetServiceRefreshInterval)
      }
      this.targetServiceRefreshInterval = setInterval(() => {
        this.loadTargetServiceData()
      }, 5000) // 每5秒刷新一次
    },

    // 停止目标服务数据刷新
    stopTargetServiceRefresh() {
      if (this.targetServiceRefreshInterval) {
        clearInterval(this.targetServiceRefreshInterval)
        this.targetServiceRefreshInterval = null
      }
    },

    back() {
      window.history.back();
    },

    // 处理导出命令
    async handleExportCommand(command) {
      if (!this.reportData.id) {
        this.$message.warning('请先加载报告数据');
        return;
      }

      // 只有Excel导出功能已实现，其他功能显示友好提示
      if (command !== 'excel') {
        this.$message.info(`${command === 'html' ? 'HTML报告' : command === 'pdf' ? 'PDF报告' : '原始数据'}导出功能即将上线，敬请期待！`);
        return;
      }

      this.tableLoading = true;
      try {
        let response;
        let filename = `性能测试报告_${this.reportData.reportName}_${new Date().toISOString().slice(0, 10)}`;

        switch (command) {
          case 'excel':
            response = await this.$api.exportSingleReport(this.reportData.id);
            filename += '.xlsx';
            break;
          case 'html':
            // 使用模拟的HTML导出
            response = await this.mockGenerateHtmlReport();
            filename += '.html';
            break;
          case 'pdf':
            // 使用模拟的PDF导出
            response = await this.mockGeneratePdfReport();
            filename += '.pdf';
            break;
          case 'raw':
            response = await this.$api.exportTestData({
              report_id: this.reportData.id,
              format: 'json'
            });
            filename += '.json';
            break;
          default:
            this.$message.warning('未知的导出格式');
            return;
        }

        if (response && response.status === 200) {
          // 创建下载链接
          const blob = new Blob([response.data]);
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = filename;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);

          this.$message.success('报告导出成功');
        }
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        this.tableLoading = false;
      }
    },

    // 模拟HTML报告生成
    async mockGenerateHtmlReport() {
      return new Promise((resolve) => {
        setTimeout(() => {
          const htmlContent = this.generateHtmlReportContent();
          resolve({
            status: 200,
            data: htmlContent
          });
        }, 1000);
      });
    },

    // 模拟PDF报告生成
    async mockGeneratePdfReport() {
      return new Promise((resolve) => {
        setTimeout(() => {
          const pdfContent = `PDF报告内容 - ${this.reportData.reportName}`;
          resolve({
            status: 200,
            data: pdfContent
          });
        }, 1500);
      });
    },


    // 处理通知命令
    async handleNotificationCommand(command) {
      this.showNotificationDialog(command);
    },

    // 显示通知配置对话框
    showNotificationDialog() {
      // 初始化通知数据
      this.notificationDialogData = {
        visible: true,
        pushType: 'wechat', // 默认选择微信
        name: `${this.reportData.reportName}性能测试报告通知`,
        webhook: '',
        recipients: [],
      };
    },

    // 取消通知
    cancelNotification() {
      this.notificationDialogData.visible = false;
      this.$refs.notificationFormRef?.resetFields();
    },

    // 确认发送通知
    async confirmSendNotification() {
      if (!this.$refs.notificationFormRef) return;
      
      this.$refs.notificationFormRef.validate(async (valid) => {
        if (valid) {
          this.notificationDialogData.visible = false;
          await this.sendNotification(this.notificationDialogData.pushType);
        } else {
          return false;
        }
      });
    },

    // 发送通知
    async sendNotification(type) {
      this.$message.info('敬请期待！通知功能正在开发中...');
    },


    // 模拟发送通知（用于演示）
    async mockSendNotification(params) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ status: 200, data: { message: '通知发送成功' } });
        }, 1000);
      });
    },
    
    // 生成通知内容
    generateNotificationContent() {
      // 格式化性能测试报告的通知内容
      const data = this.reportData;
      const formattedTime = this.formatTime(data.endTime || data.createTime || new Date());
      const statusText = this.getStatusText(data.reportStatus);
      const successRate = this.getSuccessRate();
      
      let content = `## 性能测试报告: ${data.reportName}\n\n`;
      content += `**测试状态**: ${statusText}\n`;
      content += `**完成时间**: ${formattedTime}\n\n`;
      
      content += `### 性能指标\n`;
      content += `- 平均响应时间: ${this.formatResponseTime(data.avgResponseTime)}\n`;
      content += `- 平均TPS: ${(data.avgTps || 0).toFixed(2)}\n`;
      content += `- 成功率: ${successRate}%\n`;
      
      if (data.maxResponseTime) {
        content += `- 最大响应时间: ${this.formatResponseTime(data.maxResponseTime)}\n`;
      }
      
      if (data.totalRequests) {
        content += `- 总请求数: ${data.totalRequests}\n`;
      }
      
      if (data.duration) {
        content += `- 测试持续时间: ${data.duration}秒\n`;
      }
      
      if (data.maxUsers || data.avgUsers) {
        content += `- 并发用户数: ${data.maxUsers || data.avgUsers}\n`;
      }
      
      if (data.avgCpu || data.avgMemory) {
        content += `\n### 资源使用情况\n`;
        if (data.avgCpu) {
          content += `- 平均CPU使用率: ${data.avgCpu}%\n`;
        }
        if (data.avgMemory) {
          content += `- 平均内存使用率: ${data.avgMemory}%\n`;
        }
      }
      
      // 添加测试结果分析
      if (this.desc && this.desc !== '暂无分析结果') {
        content += `\n### 分析结果\n`;
        content += this.desc.split('\n').map(line => `> ${line}`).join('\n');
      }
      
      return content;
    },

    refreshGUI() {
      if (this.guiUrl) {
        // 强制刷新iframe
        const iframe = document.querySelector('.iframe-container iframe');
        if (iframe) {
          // 重新赋值src强制刷新
          iframe.src = this.guiUrl;
        }
        this.iframeError = false;
        this.iframeErrorMessage = '';
      } else {
        this.$message.warning('没有可用的GUI URL');
      }
    },

    handleIframeLoad() {
      this.iframeError = false;
      this.iframeErrorMessage = '';
    },

    handleIframeError() {
      this.iframeError = true;
      this.iframeErrorMessage = `无法加载GUI界面：${this.guiUrl}，请检查服务器状态`;
    },

    retryLoadGUI() {
      this.refreshGUI();
    },


    // 测试状态相关方法
    getTestStatusType() {
      if (this.isTestRunning) {
        return 'info';
      } else if (this.reportData.reportStatus === '0') {
        return 'success';
      } else {
        return 'warning';
      }
    },

    getTestStatusText() {
      if (this.isTestRunning) {
        return '运行中';
      } else if (this.reportData.reportStatus === '0') {
        return '已完成';
      } else {
        return '未运行';
      }
    },

    getTestNotRunningMessage() {
      if (this.reportData.reportStatus === '0') {
        return 'GUI界面只在测试运行时可用。此测试已完成，无法显示实时GUI界面。';
      }
      return 'GUI界面需要在性能测试运行时才能访问。请先启动性能测试，然后返回查看GUI监控界面。';
    },

    // 不再需要获取服务器名称方法


    // 处理更多操作命令
    async handleMoreCommand(command) {
      try {
        switch (command) {
          case 'baseline':
            await this.createBaseline();
            break;
          case 'compare':
            await this.compareWithBaseline();
            break;
          case 'analyze':
            await this.analyzePerformance();
            break;
          case 'config':
            this.showTestConfig();
            break;
          default:
            this.$message.warning('未知的操作类型');
        }
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败: ' + (error.message || '未知错误'));
      }
    },

    // 创建基准线
    async createBaseline() {
      try {
        // 打开基准线创建对话框
        this.baselineDialogData = {
          visible: true,
          loading: false,
          mode: 'create',
          form: {
          name: `${this.reportData.reportName}_基准线`,
          description: '基于当前报告创建的性能基准线',
            task_id: this.reportData.task?.id || this.reportData.taskId,
            avg_response_time: this.reportData.avgResponseTime || 0,
            avg_tps: this.reportData.avgTps || 0,
            success_rate: this.getSuccessRate() || 0,
            avg_cpu: this.reportData.avgCpu || 0,
            avg_memory: this.reportData.avgMemory || 0,
            is_active: true,
            project_id: this.reportData.project?.id || this.$route.params.projectId
          }
        };
      } catch (error) {
        this.$message.error('准备创建基准线失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      }
    },
    
    // 提交创建基准线表单
    async submitBaselineForm() {
      try {
        // 表单验证
        await this.$refs.baselineFormRef.validate();
        
        this.baselineDialogData.loading = true;
        
        const params = { ...this.baselineDialogData.form };
        
        // 添加报告ID (自动创建基准线API需要)
        if (this.baselineDialogData.mode === 'create') {
          params.report_id = this.reportData.id;
        }
        
        // 调用API
        const response = await this.$api.createBaseline(params);

        if (response.status === 200 || response.status === 201) {
          this.$message.success('基准线创建成功');
          this.baselineDialogData.visible = false;
        }
      } catch (error) {
        this.$message.error('创建基准线失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        this.baselineDialogData.loading = false;
      }
    },

    // 与基准线对比
    async compareWithBaseline() {
      try {
        // 获取基准线列表
        const response = await this.$api.getBaselines({
          project_id: this.reportData.project?.id || this.$route.params.projectId,
          task_id: this.reportData.task?.id || this.reportData.taskId,
          is_active: true
          });

          if (response.status === 200) {
          let baselineList = [];
          
          // 处理不同的数据结构
          if (response.data.results && Array.isArray(response.data.results)) {
            baselineList = response.data.results;
          } else if (Array.isArray(response.data)) {
            baselineList = response.data;
          } else if (response.data.baselines && Array.isArray(response.data.baselines)) {
            baselineList = response.data.baselines;
          }

          if (baselineList.length > 0) {
            // 打开基准线选择对话框
            this.baselineCompareDialogData = {
              visible: true,
              loading: false,
              baselineList,
              selectedBaselineId: baselineList[0].id
            };
        } else {
          this.$message.warning('暂无可用的基准线，请先创建基准线');
          }
        }
      } catch (error) {
        this.$message.error('获取基准线列表失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      }
    },

    // 提交基准线对比
    async submitCompareBaseline() {
      try {
        if (!this.baselineCompareDialogData.selectedBaselineId) {
          this.$message.warning('请选择要对比的基准线');
          return;
        }

        this.baselineCompareDialogData.loading = true;

        try {
          // 直接使用选中的基准线数据，避免调用可能存在问题的API
          const selectedBaseline = this.baselineCompareDialogData.baselineList.find(
            baseline => baseline.id === this.baselineCompareDialogData.selectedBaselineId
          );


          let baselineData = {};
          if (selectedBaseline) {
            baselineData = selectedBaseline;
          } else {
            // 如果找不到基准线数据，尝试从API获取，但可能失败
            try {
              const baselineDetailResponse = await this.$api.getBaselineDetail(this.baselineCompareDialogData.selectedBaselineId);

              
              // 提取基准线数据
              if (baselineDetailResponse.status === 200) {
                if (baselineDetailResponse.data.baseline) {
                  baselineData = baselineDetailResponse.data.baseline;
                } else if (baselineDetailResponse.data) {
                  baselineData = baselineDetailResponse.data;
                }
              }
            } catch (detailError) {
              console.error('获取基准线详情失败:', detailError);
              // 不阻止继续执行，继续使用空的baselineData
            }
          }

          // 调用对比API
          const response = await this.$api.compareWithBaseline(this.reportData.id, {
            baseline_id: this.baselineCompareDialogData.selectedBaselineId
          });

          if (response.status === 200) {
            // 关闭选择对话框
            this.baselineCompareDialogData.visible = false;
            
            // 处理对比结果数据
            const comparisonResult = response.data;
            
            // 使用基准线详情数据构建指标
            const baselineMetrics = {
              avg_response_time: baselineData.response_time !== undefined ? this.safeParseFloat(baselineData.response_time) : this.safeParseFloat(baselineData.avg_response_time),
              avg_tps: baselineData.tps !== undefined ? this.safeParseFloat(baselineData.tps) : this.safeParseFloat(baselineData.avg_tps),
              success_rate: baselineData.error_rate !== undefined ? this.safeParseFloat(100 - baselineData.error_rate) : this.safeParseFloat(baselineData.success_rate),
              avg_cpu: this.safeParseFloat(baselineData.cpu_usage || baselineData.avg_cpu),
              avg_memory: this.safeParseFloat(baselineData.memory_usage || baselineData.avg_memory)
            };

            // 确保API返回的基准线指标可用
            let apiBaselineMetrics = null;
            if (comparisonResult.baseline_metrics) {
              apiBaselineMetrics = {
                avg_response_time: this.safeParseFloat(comparisonResult.baseline_metrics.avg_response_time || comparisonResult.baseline_metrics.response_time),
                avg_tps: this.safeParseFloat(comparisonResult.baseline_metrics.avg_tps || comparisonResult.baseline_metrics.tps),
                success_rate: comparisonResult.baseline_metrics.success_rate !== undefined ? 
                  this.safeParseFloat(comparisonResult.baseline_metrics.success_rate) : 
                  (comparisonResult.baseline_metrics.error_rate !== undefined ? 
                    this.safeParseFloat(100 - comparisonResult.baseline_metrics.error_rate) : 0),
                avg_cpu: this.safeParseFloat(comparisonResult.baseline_metrics.avg_cpu || comparisonResult.baseline_metrics.cpu_usage),
                avg_memory: this.safeParseFloat(comparisonResult.baseline_metrics.avg_memory || comparisonResult.baseline_metrics.memory_usage)
              };

            }

            // 如果API返回的基准线指标中有有效值，优先使用它们，否则使用从基准线详情构建的指标
            const finalBaselineMetrics = apiBaselineMetrics || baselineMetrics;

            
            // 显示对比结果对话框
            this.baselineCompareResultData = {
              visible: true,
              baseline_metrics: finalBaselineMetrics,
              current_metrics: comparisonResult.current_metrics || {
                avg_response_time: this.reportData.avgResponseTime || 0,
                avg_tps: this.reportData.avgTps || 0,
                success_rate: this.getSuccessRate() || 0,
                avg_cpu: this.reportData.avgCpu || 0,
                avg_memory: this.reportData.avgMemory || 0
              },
              conclusion: comparisonResult.conclusion || ''
            };
          }
        } catch (error) {
          console.error("API调用失败，使用模拟数据:", error);
          
          // 如果API调用失败，使用模拟数据
          this.baselineCompareDialogData.visible = false;
          
          // 使用报告数据模拟对比结果
          this.baselineCompareResultData = {
            visible: true,
            baseline_metrics: {
              avg_response_time: 180.50,
              avg_tps: 85.75,
              success_rate: 99.2,
              avg_cpu: 45.3, 
              avg_memory: 60.8
            },
            current_metrics: {
              avg_response_time: this.reportData.avgResponseTime || 200,
              avg_tps: this.reportData.avgTps || 80,
              success_rate: this.getSuccessRate() || 98,
              avg_cpu: this.reportData.avgCpu || 50,
              avg_memory: this.reportData.avgMemory || 65
            },
            conclusion: ''
          };
        }
      } catch (error) {
        this.$message.error('基准线对比失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        this.baselineCompareDialogData.loading = false;
      }
    },

    // 性能分析
    async analyzePerformance() {
      try {
        // 使用实际报告数据进行分析
        const analysisResult = this.generateRealAnalysis(this.reportData);

          this.$message.success('性能分析完成，请查看分析结果');


        // 显示分析结果对话框
        this.showAnalysisResults(analysisResult);
      } catch (error) {
        this.$message.error('性能分析失败: ' + (error.message || '未知错误'));
      }
    },

    // 基于实际报告数据生成性能分析
    generateRealAnalysis(reportData) {
      // 计算性能得分
      let performanceScore = 0;
      const bottlenecks = [];
      const recommendations = [];
      
      // 分析响应时间
      const avgResponseTime = this.safeParseFloat(reportData.avgResponseTime);
      if (avgResponseTime > 0) {
        // 根据响应时间评分 (小于100ms非常好，100-300ms好，300-500ms一般，>500ms需改进)
        let responseTimeScore = 0;
        if (avgResponseTime < 100) {
          responseTimeScore = 25;
        } else if (avgResponseTime < 300) {
          responseTimeScore = 20;
          recommendations.push('当前响应时间表现良好，但仍有优化空间。考虑优化数据库查询和索引。');
        } else if (avgResponseTime < 500) {
          responseTimeScore = 15;
          bottlenecks.push({ 
            type: '响应时间', 
            severity: 'medium', 
            description: `平均响应时间(${avgResponseTime.toFixed(2)}ms)偏高，建议优化数据库查询和应用代码`
          });
          recommendations.push('优化关键API响应时间，检查慢查询并优化数据库索引。');
        } else {
          responseTimeScore = 10;
          bottlenecks.push({ 
            type: '响应时间', 
            severity: 'high', 
            description: `平均响应时间(${avgResponseTime.toFixed(2)}ms)过高，严重影响用户体验`
          });
          recommendations.push('紧急优化响应时间：检查并优化数据库查询，考虑增加缓存层，优化应用代码。');
        }
        performanceScore += responseTimeScore;
      }
      
      // 分析TPS
      const avgTps = this.safeParseFloat(reportData.avgTps);
      if (avgTps > 0) {
        // 基于并发用户数评估TPS表现
        const userCount = this.safeParseFloat(reportData.maxUsers || reportData.avgUsers);
        const expectedTps = Math.max(userCount / 3, 1); // 简单估算：每个用户每3秒发起一个请求
        
        let tpsScore = 0;
        if (avgTps >= expectedTps * 1.5) {
          tpsScore = 25;
          recommendations.push('系统吞吐量表现优秀，可以考虑进一步增加并发用户数进行压测。');
        } else if (avgTps >= expectedTps) {
          tpsScore = 20;
          recommendations.push('系统吞吐量表现良好，符合预期。');
        } else if (avgTps >= expectedTps * 0.7) {
          tpsScore = 15;
          bottlenecks.push({ 
            type: 'TPS', 
            severity: 'medium', 
            description: `平均TPS(${avgTps.toFixed(2)})低于预期，系统吞吐能力有待提高`
          });
          recommendations.push('提高系统吞吐量：优化关键服务代码，考虑使用异步处理非关键请求。');
        } else {
          tpsScore = 10;
          bottlenecks.push({ 
            type: 'TPS', 
            severity: 'high', 
            description: `平均TPS(${avgTps.toFixed(2)})远低于预期，系统吞吐能力严重不足`
          });
          recommendations.push('系统吞吐量亟需提升：检查系统瓶颈，考虑服务扩容或重构关键组件。');
        }
        performanceScore += tpsScore;
      }
      
      // 分析错误率
      const errorRate = this.safeParseFloat(reportData.errorRate);
      let successRate = 100 - errorRate;
      if (errorRate !== undefined) {
        let errorScore = 0;
        if (errorRate < 0.1) {
          errorScore = 25;
        } else if (errorRate < 1) {
          errorScore = 20;
        } else if (errorRate < 5) {
          errorScore = 15;
          bottlenecks.push({ 
            type: '错误率', 
            severity: 'medium', 
            description: `错误率(${errorRate.toFixed(2)}%)略高，影响系统稳定性`
          });
          recommendations.push('改善错误处理机制，增加服务异常监控，优化异常情况下的重试逻辑。');
        } else {
          errorScore = 5;
          bottlenecks.push({ 
            type: '错误率', 
            severity: 'high', 
            description: `错误率(${errorRate.toFixed(2)}%)过高，系统稳定性差`
          });
          recommendations.push('紧急修复高错误率问题：完善错误处理，增加容错机制，优化系统稳定性。');
        }
        performanceScore += errorScore;
      }
      
      // 分析资源使用情况
      const avgCpu = this.safeParseFloat(reportData.avgCpu);
      if (avgCpu > 0) {
        let cpuScore = 0;
        if (avgCpu < 60) {
          cpuScore = 15;
        } else if (avgCpu < 80) {
          cpuScore = 10;
          bottlenecks.push({ 
            type: 'CPU使用率', 
            severity: 'low', 
            description: `CPU使用率(${avgCpu.toFixed(2)}%)较高，但仍在可接受范围内`
          });
        } else {
          cpuScore = 5;
          bottlenecks.push({ 
            type: 'CPU使用率', 
            severity: 'high', 
            description: `CPU使用率(${avgCpu.toFixed(2)}%)过高，可能成为系统瓶颈`
          });
          recommendations.push('降低CPU使用率：优化计算密集型代码，考虑增加服务器资源或负载均衡。');
        }
        performanceScore += cpuScore;
      }
      
      const avgMemory = this.safeParseFloat(reportData.avgMemory);
      if (avgMemory > 0) {
        let memoryScore = 0;
        if (avgMemory < 70) {
          memoryScore = 10;
        } else if (avgMemory < 85) {
          memoryScore = 5;
          bottlenecks.push({ 
            type: '内存使用率', 
            severity: 'medium', 
            description: `内存使用率(${avgMemory.toFixed(2)}%)较高，接近警戒线`
          });
          recommendations.push('优化内存使用：检查内存泄漏，优化大对象处理，考虑增加内存容量。');
        } else {
          memoryScore = 0;
          bottlenecks.push({ 
            type: '内存使用率', 
            severity: 'high', 
            description: `内存使用率(${avgMemory.toFixed(2)}%)过高，存在OOM风险`
          });
          recommendations.push('紧急处理内存问题：排查内存泄漏，优化大数据处理逻辑，增加服务器内存。');
        }
        performanceScore += memoryScore;
      }
      
      // 如果没有足够的数据计算得分，使用默认值
      if (performanceScore === 0) {
        performanceScore = 70; // 默认得分
      }
      
      // 如果没有发现瓶颈，添加一个积极的评价
      if (bottlenecks.length === 0) {
        bottlenecks.push({ 
          type: '系统表现', 
          severity: 'low', 
          description: '未发现明显性能瓶颈，系统整体表现良好'
        });
      }
      
      // 如果没有建议，添加一些通用建议
      if (recommendations.length === 0) {
        recommendations.push('持续监控系统性能，定期进行压力测试以保持性能水平。');
        recommendations.push('考虑建立性能基准线，用于未来性能对比和评估。');
      }
      
      // 根据实际数据生成趋势分析
      const trendAnalysis = {
        response_time_trend: avgResponseTime < 300 ? '良好' : (avgResponseTime < 500 ? '需关注' : '需优化'),
        error_rate_trend: errorRate < 1 ? '稳定' : (errorRate < 5 ? '波动' : '不稳定'),
        tps_trend: avgTps > 0 ? (avgTps > 50 ? '高' : '中等') : '低'
      };
      
      // 添加针对并发用户数的建议
      if (reportData.maxUsers > 0) {
        if (errorRate < 1 && avgCpu < 70 && avgMemory < 70) {
          recommendations.push(`当前并发用户数(${reportData.maxUsers})下系统表现良好，可以考虑提高并发数进行更大规模测试。`);
        } else if (errorRate > 5 || avgCpu > 85 || avgMemory > 85) {
          recommendations.push(`当前并发用户数(${reportData.maxUsers})已接近系统负载上限，建议优化系统后再增加并发。`);
        }
      }
      
      return {
        performance_score: Math.min(Math.round(performanceScore), 100),
        bottlenecks: bottlenecks,
        recommendations: recommendations,
        trend_analysis: trendAnalysis
      };
    },

    // 显示分析结果
    showAnalysisResults(analysisData) {
      const { performance_score, bottlenecks, recommendations } = analysisData;

      // 将数据存储到组件状态中
      this.analysisDialogData = {
        visible: true,
        performance_score,
        bottlenecks,
        recommendations
      };
    },

    // 显示测试配置
    showTestConfig() {
      if (!this.reportData.task && !this.reportData.taskId) {
        this.$message.warning('无法获取测试配置信息');
        return;
      }

      this.showTestConfigDialog();
    },

    // 显示测试配置对话框
    async showTestConfigDialog() {
      try {
        // 如果没有详细的任务配置，尝试获取
        let taskConfig = this.reportData.task;


        // 将配置数据存储到组件状态中
        this.configDialogData = {
          visible: true,
          taskConfig
        };

      } catch (error) {
        console.error('获取配置失败:', error);
        this.$message.error('获取配置失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      }
    },

    // 获取当前CPU使用率
    getCurrentCpuUsage() {
      // 优先使用实时监控数据
      if (this.monitoringData && typeof this.monitoringData.cpu_percent === 'number') {
        return Number(this.monitoringData.cpu_percent).toFixed(1);
      }
      // 其次使用报告数据
      if (this.reportData && typeof this.reportData.avgCpu === 'number') {
        return Number(this.reportData.avgCpu).toFixed(1);
      }
      return '0.0';
    },

    // 获取表格行的用户数
    getUserCountForRow(row) {
      // 如果是总体行，显示当前用户数
      if (row.method === 'ALL') {
        return this.getCurrentUserCount();
      }
      
      // 对于具体接口行，如果有接口级别的用户数，使用它
      if (row.currentUsers) {
        return row.currentUsers;
      }
      
      // 否则显示总体用户数（因为用户数是全局的）
      return this.getCurrentUserCount();
    },

    // 获取当前用户数
    getCurrentUserCount() {
      // 优先使用实时数据中的用户数
      if (this.realTimeData && this.realTimeData.total && this.realTimeData.total.current_users) {
        return this.realTimeData.total.current_users;
      }
      
      // 其次使用报告数据中的最大用户数（数据库存储）
      if (this.reportData.maxUsers) {
        return this.reportData.maxUsers;
      }
      
      // 再次使用平均用户数（数据库存储）
      if (this.reportData.avgUsers) {
        return Math.round(this.reportData.avgUsers);
      }
      
      // 最后从任务配置中获取设置的并发数
      if (this.reportData.task) {
        if (this.reportData.task.concurrencyNumber) {
          return this.reportData.task.concurrencyNumber;
        }
        if (this.reportData.task.users) {
          return this.reportData.task.users;
        }
      }
      
      return '-';
    },

    // 获取当前内存使用率
    getCurrentMemoryUsage() {
      // 优先使用实时监控数据
      if (this.monitoringData && typeof this.monitoringData.memory_percent === 'number') {
        return Number(this.monitoringData.memory_percent).toFixed(1);
      }
      // 其次使用报告数据
      if (this.reportData && typeof this.reportData.avgMemory === 'number') {
        return Number(this.reportData.avgMemory).toFixed(1);
      }
      return '0.0';
    },

    // 获取正确的接口名称 - 简化逻辑，直接使用Locust的格式
    getCorrectInterfaceName(key, stats) {
      // 优先使用stats中的name字段（接口路径）
      if (stats.name) {
        return stats.name;
      }
      
      // 如果stats中有path字段，使用path
      if (stats.path) {
        return stats.path;
      }
      
      // 如果key是 "GET /api/test" 格式，提取路径部分
      const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
      for (const method of httpMethods) {
        if (key.startsWith(method + ' ')) {
          return key.substring(method.length + 1);
        }
      }
      
      // 否则直接返回key
      return key;
    },

    // 获取正确的HTTP方法 - 简化逻辑
    getCorrectHttpMethod(key, stats) {
      // 优先使用stats中的method字段
      if (stats.method) {
        return stats.method;
      }
      
      // 从key中提取HTTP方法
      const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
      for (const method of httpMethods) {
        if (key.startsWith(method + ' ')) {
          return method;
        }
      }
      
      return 'N/A';
    },

    // 检查是否为HTTP方法
    isHttpMethod(value) {
      const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
      return httpMethods.includes(value?.toUpperCase());
    },

    // 从key中提取接口名称
    extractInterfaceName(key, stats) {
      // 如果stats中有path字段，优先使用
      if (stats.path) {
        return stats.path;
      }

      // 如果key包含HTTP方法，提取路径部分
      const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
      for (const method of httpMethods) {
        if (key.startsWith(method + ' ')) {
          return key.substring(method.length + 1);
        }
      }

      // 如果没有HTTP方法前缀，直接返回key
      return key;
    },

    // 获取得分颜色
    getScoreColor(score) {
      if (score >= 80) return '#67c23a';
      if (score >= 60) return '#e6a23c';
      return '#f56c6c';
    },

    // 获取严重程度类型
    getSeverityType(severity) {
      const typeMap = {
        'low': 'success',
        'medium': 'warning',
        'high': 'danger'
      };
      return typeMap[severity] || 'info';
    },

    // 保存报告
    async saveReport() {
      try {
        const params = {
          reportName: this.taskName,
          resultAnalyse: this.desc
        };

        // 使用正确的API方法
        const response = await this.$api.updateTaskReportDetail(this.reportData.id, params);

        if (response.status === 200) {
          this.$message.success('保存成功');
          // 更新本地数据
          this.reportData.reportName = this.taskName;
          this.reportData.resultAnalyse = this.desc;
        }
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      }
    },

    // 处理行点击
    handleRowClick(row, column, event) {
      // 如果点击的是复选框列，不做处理
      if (column.type === 'selection') {
        return;
      }
      
      // 仅当不是筛选模式时，点击行可以切换选择状态
      if (!this.isFilterMode) {
        // 切换行的选择状态
        this.$refs.table.toggleRowSelection(row);
      }
    },

    // 处理表格选择变化
    handleSelectionChange(val) {
      // 只更新选中的行，不做模式切换和弹窗
      this.selectedRows = val;
    },

    // 切换筛选模式
    toggleFilterMode() {
      if (!this.isFilterMode) {
        // 进入筛选模式，强制同步selectedRows
        const checkedRows = this.$refs.table.getSelectionRows ? this.$refs.table.getSelectionRows() : [];
        if (checkedRows.length === 0) {
          this.$message.warning('请先勾选需要查看的接口');
          return;
        }
        this.selectedRows = checkedRows;
        this.isFilterMode = true;
        this.$message.success(`已筛选 ${this.selectedRows.length} 个接口，图表和数据表已更新`);
      } else {
        // 退出筛选模式，但保留选中状态
        this.isFilterMode = false;
        // 不再清除表格选择状态
        // if (this.$refs.table) {
        //   this.$refs.table.clearSelection();
        // }
        // 不再清空selectedRows
        // this.selectedRows = [];
        this.$message.info('已显示全部数据，保留已选中的接口');
      }
    },

    setMonitorIframeUrl() {
      if (!this.monitorUrl || !/^https?:\/\//.test(this.monitorUrl)) {
        this.$message.warning('请输入以 http:// 或 https:// 开头的有效链接');
        return;
      }
      this.monitorIframeUrl = this.monitorUrl;
    },
    resetMonitorIframeUrl() {
      this.monitorUrl = '';
      this.monitorIframeUrl = '';
    },
    
    // 获取对比值的CSS类
    getComparisonClass(currentValue, baselineValue, metricType) {
      // 确保值是有效的数字
      const current = parseFloat(currentValue) || 0;
      const baseline = parseFloat(baselineValue) || 0;
      
      if (baseline === 0) {
        // 如果基准值为0，只能比较绝对值
        if (current === 0) return 'comparison-similar';
        return ['avg_tps', 'tps', 'success_rate'].includes(metricType) ? 
          'comparison-better' : 'comparison-worse';
      }
      
      // 定义指标越低越好还是越高越好
      const higherIsBetter = ['avg_tps', 'tps', 'success_rate'].includes(metricType);
      const diff = ((current - baseline) / baseline) * 100;
      
      // 10%的阈值来判断好坏
      if (higherIsBetter) {
        if (diff >= 10) return 'comparison-better';
        if (diff <= -10) return 'comparison-worse';
        return 'comparison-similar';
      } else {
        if (diff <= -10) return 'comparison-better';
        if (diff >= 10) return 'comparison-worse';
        return 'comparison-similar';
      }
    },
    
    // 获取对比值的文本
    getComparisonText(currentValue, baselineValue, metricType) {
      // 确保值是有效的数字
      const current = parseFloat(currentValue) || 0;
      const baseline = parseFloat(baselineValue) || 0;
      
      if (baseline === 0) {
        // 如果基准值为0，只显示绝对差异
        return current === 0 ? '0 (0%)' : `+${current.toFixed(2)} (-)`;
      }
      
      const diff = current - baseline;
      const percentDiff = ((diff / baseline) * 100).toFixed(1);
      const diffText = diff >= 0 ? `+${diff.toFixed(2)}` : diff.toFixed(2);
      const percentText = diff >= 0 ? `+${percentDiff}%` : `${percentDiff}%`;
      
      return `${diffText} (${percentText})`;
    },
    
    // 生成对比结论
    generateComparisonConclusion() {
      const metrics = this.baselineCompareResultData;
      if (!metrics || !metrics.current_metrics || !metrics.baseline_metrics) {
        return '无法生成对比结论，数据不完整。';
      }
      
      const current = metrics.current_metrics;
      const baseline = metrics.baseline_metrics;
      
      let conclusion = '性能对比分析：\n';
      
      // 响应时间分析
      if (current.avg_response_time !== undefined && baseline.avg_response_time !== undefined && baseline.avg_response_time > 0) {
      const responseTimeDiff = ((current.avg_response_time - baseline.avg_response_time) / baseline.avg_response_time) * 100;
      if (responseTimeDiff > 10) {
        conclusion += `• 响应时间较基准线增加了${responseTimeDiff.toFixed(1)}%，性能有所下降。\n`;
      } else if (responseTimeDiff < -10) {
        conclusion += `• 响应时间较基准线减少了${Math.abs(responseTimeDiff).toFixed(1)}%，性能有所提升。\n`;
      } else {
        conclusion += `• 响应时间与基准线相比基本持平，波动在${Math.abs(responseTimeDiff).toFixed(1)}%范围内。\n`;
        }
      } else {
        conclusion += `• 响应时间数据不完整，无法进行比较。\n`;
      }
      
      // TPS分析
      if (current.avg_tps !== undefined && baseline.avg_tps !== undefined && baseline.avg_tps > 0) {
      const tpsDiff = ((current.avg_tps - baseline.avg_tps) / baseline.avg_tps) * 100;
      if (tpsDiff > 10) {
        conclusion += `• TPS较基准线提高了${tpsDiff.toFixed(1)}%，吞吐能力有所提升。\n`;
      } else if (tpsDiff < -10) {
        conclusion += `• TPS较基准线下降了${Math.abs(tpsDiff).toFixed(1)}%，吞吐能力有所下降。\n`;
      } else {
        conclusion += `• TPS与基准线相比基本持平，波动在${Math.abs(tpsDiff).toFixed(1)}%范围内。\n`;
        }
      } else {
        conclusion += `• TPS数据不完整，无法进行比较。\n`;
      }
      
      // 成功率分析
      if (current.success_rate !== undefined && baseline.success_rate !== undefined) {
      const successRateDiff = current.success_rate - baseline.success_rate;
      if (successRateDiff > 1) {
        conclusion += `• 成功率较基准线提高了${successRateDiff.toFixed(1)}个百分点，系统稳定性有所提升。\n`;
      } else if (successRateDiff < -1) {
        conclusion += `• 成功率较基准线下降了${Math.abs(successRateDiff).toFixed(1)}个百分点，系统稳定性有所下降。\n`;
      } else {
        conclusion += `• 成功率与基准线相比基本持平，系统稳定性保持一致。\n`;
        }
      } else {
        conclusion += `• 成功率数据不完整，无法进行比较。\n`;
      }
      
      // 资源使用分析
      if (current.avg_cpu !== undefined && baseline.avg_cpu !== undefined && baseline.avg_cpu > 0) {
        const cpuDiff = ((current.avg_cpu - baseline.avg_cpu) / baseline.avg_cpu) * 100;
        if (cpuDiff > 10) {
          conclusion += `• CPU使用率较基准线增加了${cpuDiff.toFixed(1)}%，可能需要关注资源使用情况。\n`;
        } else if (cpuDiff < -10) {
          conclusion += `• CPU使用率较基准线减少了${Math.abs(cpuDiff).toFixed(1)}%，资源利用效率有所提升。\n`;
        } else {
          conclusion += `• CPU使用率与基准线相比基本持平。\n`;
        }
      }
      
      if (current.avg_memory !== undefined && baseline.avg_memory !== undefined && baseline.avg_memory > 0) {
        const memoryDiff = ((current.avg_memory - baseline.avg_memory) / baseline.avg_memory) * 100;
        if (memoryDiff > 10) {
          conclusion += `• 内存使用率较基准线增加了${memoryDiff.toFixed(1)}%，可能需要关注内存占用情况。\n`;
        } else if (memoryDiff < -10) {
          conclusion += `• 内存使用率较基准线减少了${Math.abs(memoryDiff).toFixed(1)}%，内存利用效率有所提升。\n`;
        } else {
          conclusion += `• 内存使用率与基准线相比基本持平。\n`;
        }
      }
      
      // 总体结论
      let performanceIssues = [];
      
      if (current.avg_response_time !== undefined && baseline.avg_response_time !== undefined && baseline.avg_response_time > 0) {
        const responseTimeDiff = ((current.avg_response_time - baseline.avg_response_time) / baseline.avg_response_time) * 100;
        if (responseTimeDiff > 10) performanceIssues.push('响应时间增加');
      }
      
      if (current.avg_tps !== undefined && baseline.avg_tps !== undefined && baseline.avg_tps > 0) {
        const tpsDiff = ((current.avg_tps - baseline.avg_tps) / baseline.avg_tps) * 100;
        if (tpsDiff < -10) performanceIssues.push('TPS下降');
      }
      
      if (current.success_rate !== undefined && baseline.success_rate !== undefined) {
        const successRateDiff = current.success_rate - baseline.success_rate;
        if (successRateDiff < -1) performanceIssues.push('成功率下降');
      }
      
      const issueCount = performanceIssues.length;
      
      if (issueCount === 0) {
        conclusion += '\n总体结论：当前性能测试结果与基准线相比表现良好，未发现明显性能退化。';
      } else if (issueCount === 1) {
        conclusion += `\n总体结论：当前性能测试结果与基准线相比存在${performanceIssues[0]}的情况，建议关注上述性能变化。`;
      } else {
        conclusion += `\n总体结论：当前性能测试结果与基准线相比存在多项指标下降（${performanceIssues.join('、')}），建议详细分析性能变化原因。`;
      }
      
      return conclusion;
    },
    
    // 导出对比报告
    async exportComparisonResult() {
      try {
        this.$message.info('正在准备导出对比报告...');
        
        // 构建导出参数
        const params = {
          report_id: this.reportData.id,
          baseline_id: this.baselineCompareDialogData.selectedBaselineId,
          format: 'pdf',
          include_charts: true
        };
        
        // 此处应调用实际的导出API
        // const response = await this.$api.exportComparisonReport(params);
        
        // 模拟导出成功
        setTimeout(() => {
          this.$message.success('对比报告导出成功');
        }, 1500);
        
      } catch (error) {
        this.$message.error('导出对比报告失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      }
    },

    // 安全解析浮点数值，避免NaN、Infinity等值导致的JSON序列化问题
    safeParseFloat(value) {
      if (value === undefined || value === null) {
        return 0;
      }
      
      // 尝试转换字符串"null"、"undefined"等特殊值
      if (value === "null" || value === "undefined" || value === "") {
        return 0;
      }
      
      const num = parseFloat(value);
      
      // 检查是否为有效的有限数值
      if (isNaN(num) || !isFinite(num)) {
        return 0;
      }
      
      return num;
    },
  },
  mounted() {
    (async () => {
      // 首先获取报告ID - 支持多种方式获取
      this.reportId = this.$route.params.id || this.$route.query.id || this.$route.query.reportId

      if (!this.reportId) {
        this.$message.error('报告ID不能为空，请从报告列表页面进入')
        // 跳转回报告列表页面
        this.$router.push({ name: 'PerformanceResult' })
        return
      }

      // 加载报告数据
      await this.loadReportData()
      // 默认显示指标详情
      this.activeIndex = '1'
    })();
  },
  beforeUnmount() {
    // 清理WebSocket连接和定时器
    this.stopAllRealTimeUpdates();
  }
}
</script>

<style scoped>
/* 基准线对话框样式 */
.baseline-info-hint {
  background-color: #f0f9ff;
  border-left: 4px solid #409EFF;
  padding: 10px;
  margin: 10px 0;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 对比结果样式 */
.comparison-container {
  padding: 15px 0;
}

.comparison-card {
  height: 100%;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.comparison-card.baseline {
  background-color: #f0f9ff;
  border-left: 4px solid #409EFF;
}

.comparison-card.current {
  background-color: #f6ffed;
  border-left: 4px solid #67C23A;
}

.comparison-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 500;
}

.comparison-metrics .metric-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.comparison-metrics .metric-label {
  font-weight: 500;
  color: #606266;
}

.comparison-metrics .metric-value {
  font-weight: 500;
  color: #303133;
}

.comparison-better {
  margin-left: 10px;
  color: #67C23A;
  font-weight: bold;
}

.comparison-worse {
  margin-left: 10px;
  color: #F56C6C;
  font-weight: bold;
}

.comparison-similar {
  margin-left: 10px;
  color: #E6A23C;
}

.comparison-conclusion {
  margin-top: 25px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.conclusion-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
}

.conclusion-content {
  white-space: pre-line;
  line-height: 1.6;
  color: #606266;
}
/* ===== 新的现代化样式 ===== */

/* 报告头部卡片 */
.report-header-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  color: white;
  margin-bottom: 20px;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
  overflow: hidden;
}

.report-header-card :deep(.el-card__body) {
  padding: 30px;
}

.report-header-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

/* 任务信息区域 */
.task-info-section {
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.task-title-area {
  max-width: 600px;
}

.task-title-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.task-name-button {
  font-size: 24px;
  font-weight: 700;
  color: white !important;
  padding: 0;
  height: auto;
  line-height: 1.2;
}

.task-name-button:hover {
  color: rgba(255, 255, 255, 0.8) !important;
}

.edit-icon {
  margin-left: 8px;
  font-size: 18px;
  opacity: 0.7;
}

.task-status-tag {
  font-weight: 600;
  font-size: 13px;
  padding: 6px 12px;
  border-radius: 20px;
  border: none;
}

.task-status-tag.success {
  background-color: #4ade80;
  color: white;
}

.task-status-tag.running {
  background-color: #3b82f6;
  color: white;
}
.task-status-tag.danger {
  background-color: #f56c6c;
  color: white;
}
.task-status-tag.info {
  background-color: #8c8c8c;
  width: 100px;
  color: white;
}


.task-status-tag.error {
  background-color: #ef4444;
  color: white;
}

.desc-text {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  line-height: 1.6;
  cursor: default;
}

/* 指标卡片区域 */
.metrics-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.metric-card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.metric-card:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
}

.metric-icon {
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
}

.metric-content {
  flex: 1;
}

.metric-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: white;
}

.metric-values {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric-label {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

.metric-value {
  font-size: 14px;
  font-weight: 600;
  color: white;
}

/* Tab导航和按钮容器 */
.tab-navigation-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
}

.report-tabs {
  flex: 1;
  border-bottom: none;
}

.report-tabs :deep(.el-menu-item) {
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.report-tabs :deep(.el-menu-item.is-active) {
  border-bottom-color: #667eea;
  color: #667eea;
}

.report-tabs :deep(.el-menu-item:hover) {
  color: #667eea;
}

/* 操作按钮组 */
.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.action-btn {
  height: 36px;
  padding: 0 16px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-dropdown {
  margin: 0;
}

.action-dropdown .action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 下拉菜单项图标 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
}

:deep(.el-dropdown-menu__item i) {
  width: 16px;
}

/* 图表容器样式 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 50px;
  padding: 0 15px;
}

.chart-wrapper {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.03);
  position: relative;
  overflow: hidden;
}

.chart-wrapper:hover {
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.12);
  transform: translateY(-3px);
  border-color: rgba(0, 0, 0, 0.06);
}

/* 为不同类型的图表添加不同的顶部边框颜色 */
.chart-wrapper:nth-child(1) {
  border-top: 3px solid #5470c6;
}

.chart-wrapper:nth-child(2) {
  border-top: 3px solid #5b8ff9;
}

.chart-wrapper:nth-child(3) {
  border-top: 3px solid #ff6b3b;
}

.chart-wrapper:nth-child(4) {
  border-top: 3px solid #1890ff;
}

.chart-wrapper:nth-child(5) {
  border-top: 3px solid #9b8bfe;
}

.chart-wrapper:nth-child(6) {
  border-top: 3px solid #e84a5f;
}

/* 图表标题样式增强 */
.chart-wrapper :deep(.chart-title) {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
  margin-bottom: 15px;
  position: relative;
  padding-left: 12px;
}

.chart-wrapper :deep(.chart-title)::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 16px;
  width: 4px;
  border-radius: 2px;
  background-color: #5470c6;
}

/* 为不同类型的图表添加不同的标题装饰色 */
.chart-wrapper:nth-child(1) :deep(.chart-title)::before {
  background-color: #5470c6;
}

.chart-wrapper:nth-child(2) :deep(.chart-title)::before {
  background-color: #5b8ff9;
}

.chart-wrapper:nth-child(3) :deep(.chart-title)::before {
  background-color: #ff6b3b;
}

.chart-wrapper:nth-child(4) :deep(.chart-title)::before {
  background-color: #1890ff;
}

.chart-wrapper:nth-child(5) :deep(.chart-title)::before {
  background-color: #9b8bfe;
}

.chart-wrapper:nth-child(6) :deep(.chart-title)::before {
  background-color: #e84a5f;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .charts-container {
    padding: 0 10px;
  }

  .chart-wrapper {
    padding: 15px;
  }
}

/* 原有样式保持不变 */
.outer {
  padding: 20px;
}

.box {
  max-width: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .metrics-section {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .tab-navigation-container {
    flex-direction: column;
    gap: 15px;
    padding: 15px;
  }

  .action-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }

  .metrics-section {
    grid-template-columns: 1fr;
  }
}

/* 以下是原有样式，保持不变 */

.box{
  background-color: #ffffff;
}
.outer {
    background-color: #f5f7f9;
    padding: 3px;
  }
.projectInfo {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.el-tag {
  color: #ffffff;
  width: 70px;
  height: 25px;
  text-align: center;
  font-size: 13px;
  line-height: 23px;
}

.icon-info{
  width: 60px;
  height: 60px;
  background-color: #4c52d5;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.parameter{
  margin-bottom: 3px;
}

.munu{
  margin-top: 10px;
  margin-left: 15px;
  margin-bottom: 5px;
}

.spacing {
  background:#f5f7f9;
  height: 40px;
  line-height: 40px;
}

.spacing > span {
  margin-right: 50px;
  font-size: 15px;
}

.table-desc {
  margin-bottom: 7px;
  display: flex;
}

.table-desc > span {
  margin-right: 50px;
  font-size: 13px;
  line-height: 35px;
  position: relative;
  padding-left: 20px;
}

.table-desc span::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 10px;
  height: 10px;
  background-color: #a5b1ff;
  border-radius: 50%;
}

.divider {
  width: 5px;
  height: 18px;
  margin: -4px 5px 0px 0px;
  background-color: #a5b1ff;
}

.title-info {
  margin-bottom: 10px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 10px;
}

.runStop {
  margin-top: -10px;
  margin-right: 10px
}

.p_text {
  font-size: 15px;
  margin-bottom: 50px;
  background:#f5f7f9;
  height: 40px;
  line-height: 40px
}

.iframe-container {
  height: calc(100vh - 250px);
  width: 100%;
}

.iframe-container iframe {
  height: 100%;
  width: 100%;
  border: none;
}

.task-header {
  display: flex;
  flex-direction: column;
}

.task-title-container {
  display: flex;
  align-items: center;
  margin-top: -5px;
}

.task-name-button {
  font-size: 16px;
  color: #ffffff;
  font-weight: 500;
  padding: 0;
  display: flex;
  align-items: center;
  width: auto;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.edit-icon {
  margin-left: 5px;
  font-size: 14px;
}

.task-status-tag {
  margin-left: 10px;
  color: #ffffff;
  font-weight: 500;
  border: none;
  padding: 0 10px;
  height: 26px;
  line-height: 26px;
}

.task-description {
  margin-top: 10px;
}

.desc-button {
  font-size: 13px;
  color: #ffffff;
  padding: 0;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  opacity: 0.9;
}

.desc-button:hover {
  opacity: 1;
  text-decoration: underline;
}

.task-name-input {
  position: absolute;
  top: 10px;
  left: 20px;
  width: 170px;
  z-index: 10;
}

/* 监控面板样式 */
.monitor-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.monitor-card {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.monitor-card h4 {
  margin: 0 0 15px 0;
  color: #409eff;
  font-size: 16px;
  border-bottom: 2px solid #e4e7ed;
  padding-bottom: 8px;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.metric-item:last-child {
  border-bottom: none;
}

.metric-normal {
  color: #67c23a;
  font-weight: bold;
}

.metric-warning {
  color: #e6a23c;
  font-weight: bold;
}

.metric-danger {
  color: #f56c6c;
  font-weight: bold;
}

/* 日志面板样式 */
.log-controls {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.log-container {
  height: 500px;
  max-height: 500px;
  overflow-y: auto;
  background: #1e1e1e;
  border-radius: 4px;
  padding: 10px;
}

.log-item {
  margin-bottom: 8px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  padding: 4px 8px;
  border-radius: 3px;
  position: relative;
}

.log-item:hover {
  background-color: rgba(255, 255, 255, 0.05);
}

.log-time {
  color: #6c757d;
  margin-right: 8px;
}

.log-level {
  margin-right: 8px;
  font-weight: bold;
}

.log-category {
  display: inline-flex;
  align-items: center;
  margin-right: 8px;
  color: #909399;
}

.log-message {
  color: #ffffff;
}

.log-method {
  display: inline-block;
  padding: 1px 6px;
  border-radius: 3px;
  font-weight: bold;
  margin-right: 8px;
}

.method-get {
  background-color: #61affe;
  color: #fff;
}

.method-post {
  background-color: #49cc90;
  color: #fff;
}

.method-put {
  background-color: #fca130;
  color: #fff;
}

.method-delete {
  background-color: #f93e3e;
  color: #fff;
}

.method-patch {
  background-color: #50e3c2;
  color: #fff;
}

.method-head, .method-options {
  background-color: #9012fe;
  color: #fff;
}

.log-url {
  color: #e6db74;
  margin-right: 8px;
}

.log-status {
  display: inline-block;
  padding: 1px 6px;
  border-radius: 3px;
  font-weight: bold;
}

.status-success {
  background-color: #49cc90;
  color: #fff;
}

.status-redirect {
  background-color: #fca130;
  color: #fff;
}

.status-client-error {
  background-color: #f93e3e;
  color: #fff;
}

.status-server-error {
  background-color: #d41f1c;
  color: #fff;
}

.details-toggle {
  position: absolute;
  right: 8px;
  top: 4px;
  font-size: 11px;
  padding: 0;
  color: #909399;
}

.log-details {
  margin-top: 5px;
  padding: 8px;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
  white-space: pre-wrap;
  font-size: 11px;
  color: #a9b7c6;
  max-height: 200px;
  overflow-y: auto;
}

.log-info .log-level {
  color: #17a2b8;
}

.log-warning .log-level {
  color: #ffc107;
}

.log-error .log-level {
  color: #dc3545;
}

.log-debug .log-level {
  color: #6c757d;
}

.no-logs {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #909399;
}

.empty-log-content {
  text-align: center;
}

.empty-log-icon {
  font-size: 48px;
  color: #606266;
  margin-bottom: 16px;
}

.empty-log-text {
  font-size: 16px;
  color: #909399;
  margin: 8px 0;
}

.empty-log-hint {
  font-size: 14px;
  color: #606266;
  margin: 4px 0;
}

.no-logs .el-empty {
  background: transparent;
}

.no-logs .el-empty__image svg {
  fill: #606266;
}

.no-logs .el-empty__description {
  color: #909399;
  font-size: 14px;
}

.no-logs :deep(.el-empty__description p) {
  color: #909399;
}

/* 错误列表样式 */
.error-list {
  max-height: 200px;
  overflow-y: auto;
}

.error-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 5px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #f56c6c;
}

.error-type {
  font-weight: bold;
  color: #f56c6c;
}

.error-count {
  background: #f56c6c;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .monitor-grid {
    grid-template-columns: 1fr;
  }

  .log-controls {
    flex-direction: column;
    gap: 10px;
  }

  .log-controls > * {
    width: 100%;
  }

  .gui-server-selection {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .gui-server-selection > * {
    width: 100%;
  }

  .gui-server-selection .el-radio-group {
    display: flex;
    justify-content: center;
  }

  .test-actions {
    flex-direction: column;
    gap: 10px;
  }

  .test-actions .el-button {
    width: 100%;
  }
}

/* 对话框样式 */
.analysis-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

.analysis-section {
  margin-bottom: 30px;
}

.analysis-section h4 {
  margin-bottom: 15px;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
}

.score-display {
  text-align: center;
  margin: 20px 0;
}

.score-text {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.recommendations-list {
  list-style: none;
  padding: 0;
}

.recommendation-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.recommendation-item:last-child {
  border-bottom: none;
}

.recommendation-icon {
  color: #67c23a;
  margin-right: 8px;
}

.config-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

.config-section {
  margin-bottom: 20px;
}

.config-section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.config-section-title .el-icon {
  margin-right: 8px;
}

.config-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.config-label {
  font-weight: 500;
  color: #606266;
  margin-right: 10px;
  min-width: 100px;
}

.config-value {
  color: #303133;
}

.notification-dialog-content {
  text-align: center;
}

.notification-info {
  margin: 20px 0;
}

.notification-confirm {
  color: #606266;
  font-size: 14px;
}

/* 通知对话框样式 */
:deep(.notification-dialog) {
  .el-message-box__content {
    max-height: 400px;
    overflow-y: auto;
  }
}

/* 配置对话框样式 */
:deep(.config-dialog) {
  .el-message-box {
    width: 80% !important;
    max-width: 1000px;
  }

  .el-message-box__content {
    max-height: 600px;
    overflow-y: auto;
    padding: 20px !important;
  }

  .el-message-box__message {
    margin: 0 !important;
  }
}

/* 配置HTML内容样式 */
:deep(.config-dialog) h3 {
  margin: 0 0 15px 0 !important;
  font-size: 16px !important;
  font-weight: 600 !important;
}

:deep(.config-dialog) pre {
  white-space: pre-wrap !important;
  word-wrap: break-word !important;
}

/* 下拉菜单样式优化 */
.projectInfo .el-dropdown {
  margin-left: 10px;
}

.projectInfo .el-button {
  margin-right: 10px;
}

.projectInfo .el-button:last-child {
  margin-right: 0;
}

.interface-name {
  font-weight: 600;
  color: #303133;
}

/* WebSocket状态指示器样式 */
.ws-status-indicator {
  margin-left: 15px;
  display: inline-block;
}

.ws-status-indicator .el-tag {
  transition: all 0.3s ease;
}

.ws-status-indicator .el-tag:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* GUI控制样式 */
.gui-controls {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.gui-server-selection {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.gui-server-selection .el-radio-group {
  background: white;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.gui-server-selection .el-input {
  min-width: 150px;
}

.gui-server-selection .el-select {
  min-width: 120px;
}

.gui-server-selection .el-button {
  white-space: nowrap;
}

.iframe-container {
  height: calc(100vh - 250px);
  width: 100%;
  position: relative;
}

.iframe-container iframe {
  height: 100%;
  width: 100%;
  border: none;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.iframe-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  text-align: center;
  max-width: 400px;
  width: 90%;
}

.no-gui-message {
  height: calc(100vh - 250px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-gui-message .el-empty {
  background: transparent;
}

/* 端口选择样式 */
.el-select .el-option.is-disabled {
  color: #c0c4cc;
  background-color: #f5f7fa;
  position: relative;
}

.el-select .el-option.is-disabled:hover {
  background-color: #f5f7fa;
}

/* 服务器选择样式优化 */
.gui-server-selection .el-select {
  margin-right: 10px;
}

.gui-server-selection .el-select .el-input__inner {
  font-size: 12px;
}

.gui-server-selection .el-button {
  font-size: 12px;
}

/* 端口状态标识 */
.port-status-available {
  color: #67c23a;
}

.port-status-occupied {
  color: #f56c6c;
}

/* 测试状态提示样式 */
.test-not-running {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.test-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.test-actions .el-button {
  min-width: 140px;
}

/* 通知对话框样式 */
.push-dialog {
  max-width: 420px !important;
  border-radius: 12px;
  padding-bottom: 0;
}
.push-dialog .el-dialog__body {
  padding: 24px 32px 0 32px !important;
}
.push-dialog .el-form-item {
  margin-bottom: 22px;
}
.push-dialog .el-form-item__label {
  font-weight: 600;
  color: #333;
  font-size: 15px;
}
.push-dialog .custom-radio-group {
  display: flex;
  gap: 12px;
}
.push-dialog .custom-radio-btn {
  cursor: pointer;
  padding: 7px 18px;
  border-radius: 6px;
  border: 1.5px solid #e0e7ef;
  background: #f7f8fa;
  color: #666;
  font-weight: 500;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
}
.push-dialog .custom-radio-btn.active,
.push-dialog .custom-radio-btn:hover {
  border-color: #6366f1;
  background: #eef2ff;
  color: #3b3b7a;
  box-shadow: 0 2px 8px rgba(99,102,241,0.08);
}
.push-dialog .form-tip {
  font-size: 12px;
  color: #b0b0b0;
  margin-top: 2px;
}
.push-dialog .el-input,
.push-dialog .el-select {
  width: 100%;
}
.push-dialog .el-descriptions {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px 10px 2px 10px;
  margin-top: 8px;
}
.push-dialog .el-descriptions__label {
  color: #888;
  font-weight: 500;
}
.push-dialog .el-descriptions__content {
  color: #222;
  font-weight: 600;
}
.push-dialog .dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 18px 32px 18px 32px;
  background: #f7f8fa;
  border-radius: 0 0 12px 12px;
  margin-top: 0;
}
.push-dialog .el-button {
  min-width: 90px;
}

/* 现代通知对话框 */
.modern-notification-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.modern-notification-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #3a8ee6, #5b5ef4);
  color: white;
  padding: 18px 24px;
  margin: 0;
}

.modern-notification-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.modern-notification-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: rgba(255, 255, 255, 0.9);
}

.modern-notification-dialog :deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  color: white;
}

.modern-notification-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.notification-dialog-content {
  padding: 0;
}

.notification-dialog-header {
  padding: 20px 30px;
  background-color: #f8fafc;
  border-bottom: 1px solid #ebeef5;
}

.notification-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.notification-icon {
  font-size: 20px;
  color: #3a8ee6;
}

.notification-subtitle {
  color: #606266;
  font-size: 14px;
}

.notification-form {
  padding: 20px 30px;
}

.notification-input :deep(.el-input__inner) {
  border-radius: 8px;
  padding: 12px;
  height: 44px;
}

.notification-select :deep(.el-input__wrapper) {
  border-radius: 8px;
  padding: 12px;
  height: 44px;
}

.notification-type-selector {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 8px;
}

.notification-type-option {
  flex: 1;
  height: 70px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
  min-width: 100px;
}

.notification-type-option:hover {
  border-color: #a0cfff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.notification-type-option.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.notification-type-option span {
  font-size: 14px;
  font-weight: 500;
  text-align: center;
}

.notification-type-option .option-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  flex-shrink: 0;
}

/* 调整顺序，以确保这些样式应用在icon样式之后 */

.email-icon {
  background-color: #67c23a;
}

.webhook-icon {
  background-color: #409eff;
}

.dingtalk-icon {
  background-color: #1890ff;
}

.wechat-icon {
  background-color: #07c160;
}

.notification-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.4;
}

.notification-report-preview {
  margin-top: 16px;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.notification-report-preview .preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #f8fafc;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  font-weight: 600;
  color: #303133;
}

.notification-report-preview .preview-content {
  padding: 20px;
}

.notification-report-preview .preview-item {
  display: flex;
  margin-bottom: 12px;
}

.notification-report-preview .item-label {
  width: 80px;
  color: #606266;
  font-size: 14px;
}

.notification-report-preview .item-value {
  flex: 1;
  font-weight: 500;
  color: #303133;
}

.notification-report-preview .metrics-section {
  margin-top: 16px;
}

.notification-report-preview .metrics-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.notification-report-preview .metrics-row:last-child {
  margin-bottom: 0;
}

.notification-report-preview .metric-item-wide {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f8fafc;
  border-radius: 8px;
  border-left: 3px solid #409eff;
}

.notification-report-preview .metric-item-wide .metric-label {
  font-size: 14px;
  color: #606266;
}

.notification-report-preview .metric-item-wide .metric-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

.notification-dialog-footer {
  padding: 16px 30px;
  background-color: #f8fafc;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.notification-dialog-footer :deep(.el-button) {
  padding: 10px 20px;
  height: auto;
  border-radius: 8px;
}

.notification-dialog-footer :deep(.el-button--primary) {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>